What does this Do (Question on generics in java) ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gautamz07
    New Member
    • Sep 2013
    • 26

    #1

    What does this Do (Question on generics in java) ?

    A few difficulties with the below programme
    Code:
    import java.util.*;
    public class Gautam{
        public static void main(String []a)
        {
            Integer[] iray={1,2,3,4,5,6};
            Character[] bang={'G', ' ' , 'A',' ' ,'U', ' ' ,'T', ' ' ,'A',' ' ,'M'};
            Float [] Fk={1.0f, 2.0f, 4.0f};
            Double [] Google={3.3,4.5, 6.0, 9.0};
                    
            printMe(iray);
            printMe(bang);
            printMe(Fk);
            printMe(Google);
        }
        public static <T> void printMe(T[] x) 
        {
            for(T b: x)
            System.out.printf("%s" , b);
             System.out.println();
          	System.out.println();
    
        }
        
    }
    Somebody please do explain this line in the Code ?
    Code:
        public static <T> void printMe(T[] x)
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Why don't you just run it? (and post the result here)
    Then the meaning becomes obvious.
    If there is something unclear for you in the output, we then can discuss it (referring to your posted result).

    Theory:
    T is the type, and T[] is an array of the type that you passed as parameter. In your case the type is Integer, Character, Float and then Double

    Practice:
    ... (Just run it!)

    Comment

    • Nepomuk
      Recognized Expert Specialist
      • Aug 2007
      • 3111

      #3
      I think I understand what the problem is. Let me explain:

      With generics, you may want to define a function that takes a generic type that has not been defined thus far. So what you want to do is say "Hey, there's a generic type in this function and I'll be calling it T." This is what you do with the syntax you posted; so
      Code:
      public static <T> void printMe(T[] x)
      is a static function which will take an array of any type of object and, if you look at the rest of the code, print the string representations of all of the elements in that array.

      You could, if you wanted to, limit the generic type the same way you can limit generic types at other places. So for example, if you wanted to print collections rather than arrays you could use something like this:
      Code:
      public static <E, T extends Collection<E>> void printMe(T x)
      Now you have a Collection with the generic type E and you can work with that. This Collection could be a List, a Set or a Queue to name just the most common ones.

      Comment

      Working...