Generics simply explained
Java is strongly types language, you are expected to know what values you are passing at compile time.There is no control as to what objects you place in a List or a Vector for example
Vector v= new Vector();
v.add(new Vehicle);
v.add(new Mammals) ;
To create a Type safety we use Java Generics from Java 5. Generics give an ability to write general or generic code which is independent of a particular type.
Generics follow the Liskov’s Substitutability Principle4 for example I make a basket of fruits in which I can add apples,bananas, oranges & so on but if I make a basket of apples then I cannot add other fruits in it, I should disallow adding of other fruits. If basket of apples were to be inherited from basket of fruits then you could add a banana to it & also add an orange. So adding an apple to basket of apple is okay but not an orange, this will result in Runtime exception.
eg.
public static void filter(Collection take, Collection give){
boolean flag=true();
for(T obj:take)
{
if(flag)
{
give.add(obj);
}
flag=!flag;
}
}
filter() methods takes values from take & copies it to give. Usage of Filter
ArrayList<Integer> list=new ArrayList<Integer>();list.add(1);
list.add(2);
list.add(3);
ArrayList<Integer> list2=new ArrayList<Integer>();
Now I call:
filter(list,list2);System.out.println(list2.size());
Output : 2
But at the same place if you change the list2 type to Double or String then it will give you a compile time error.
Another instance of the same kind:
if you write you code this way:
ArrayList<Integer> list=new ArrayList<Integer>();list.add(“hello”);
ArrayList list2=new ArrayList();
System.out.println(list2.size());
Output : 1
Well there are a lot more to understand in Generics but this was just the basic understanding, more are like upper bounds, wildcards, lower bounds & their complexities, which will be coming up in the Java Generics course coming soon on Lets Byte Code.
To be updated please keep in touch with us & feel free to ask any doubts directly at query@letsbytecode.com







02 May 2011
Posted by Aals 

