Wednesday, February 6, 2008

Part 1 of 4 : Generics in JAVA

GENERICS:

Lets start with a Question. What is GENERICS ?
As per dictionary, it means Race , or a kind. In Java world we can say that - Introduction of Races in Collections. Lets see:

WHILE PUTTING OBJECTS INTO COLLECTION :
Before Java 5:
    List list = new ArrayList( );
    list.add(new String("JOVIAL JAVA"));
    list.add(new Integer(123455)); 
   
In Simple words, we can put Object of any type (Race) in the list.

From Java 5 onwards:
    List{String} Java5list = new ArrayList{String}( );
    Java5list.add(new String("JOVIAL JAVA"));
    Java5list.add(new Integer(123455));    ==> !!! ERROR !!!

In Simple words, only object of Race Type String can reside in list. we can also say that GENERIC Type of list is String.

WHILE FETCHING OBJECTS FROM COLLECTION :
Before Java 5:
    Object object = list.get(0);
This is true as we can put Object of any race in list, so we always get Object in return. We have to explicilty check what is the RACE of object?

    if(object instanceof String){
        System.out.println( "It was a STRING OBJECT" );
    }else{
        System.out.println( "It was not a STRING OBJECT" );
    }

From Java 5 onwards:
    String str = Java5list.get(0);

Yes, here we get String in return as the list GENERIC TYPE was STRING.


PRACTICE QUESTION :


What is true about the above code?
1. compiler error
2. compiles with warning and gives some output
3. compiles without warning and gives some output
4. compiles and runs with no output


Answer : 2


1 comment:

Anonymous said...

gr8 analogy dude between discrimantions and generics. And This will always be present till we become extinct