Generics Hmmmmm easy yet i don't understand :)

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

    Generics Hmmmmm easy yet i don't understand :)

    Code:
    import java.util.*;
    
    public class SetDemo {
    
      public static void main(String args[]) { 
         int count[] = {34, 22,10,60,30,22};
         Set<Integer> set = new HashSet<Integer>(); // What does this line really tell the compiler 
         try{
            for(int i = 0; i<5; i++){
               set.add(count[i]);
            }
            System.out.println(set);
                                 
         }
         catch(Exception e){}
      }
    }
    Set<Integer> set = new HashSet<Integer >();

    What Does The Abouve Line really do or tell the compiler .

    Code:
    public class GenericMethodTest
    {
                            
       public static < E > void printArray( E[] inputArray )
       {
          // Display array elements              
             for ( E element : inputArray ){        
                System.out.printf( "%s ", element );
             }
             System.out.println();
        }
    
        public static void main( String args[] )
        {
            // Create arrays of Integer, Double and Character
            Integer[] intArray = { 1, 2, 3, 4, 5 };
            Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
            Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
    
            System.out.println( "Array integerArray contains:" );
            printArray( intArray  ); 
    
            System.out.println( "\nArray doubleArray contains:" );
            printArray( doubleArray ); 
    
            System.out.println( "\nArray characterArray contains:" );
            printArray( charArray ); 
        } 
    }

    public static < E > void printArray( E[] inputArray )

    I Understand that becasue of the above generic meathod we don't have to write 3 overloaded meathods to print out an array of characters , integers and Double . But what does it really tell the compiler .
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    It tells the compiler that the set only contains objects of type Integer so there will be compilation errors if you try to add e.g Strings to the set.

    Comment

    Working...