12/29/2008

Generics

JDK 5.0 or any later version supports generics.
See Generics for the details.

For Collections

/* Conventional way */
List list1 = new ArrayList();
/* Generics */
List list2 = new ArrayList();
List list3 = new ArrayList();

list1.add("Conventional");
list2.add("Generics");
list3.add(new Integer(7));

String conventional = (String) list1.get(0);
String generics = list2.get(0);
/* java.lang.ClassCastException occurs */
Integer i = (Integer)list1.get(0);
/* Compile error */
Integer i2 = (Integer)list2.get(0);


About ClassCastException
If you cast an object to a type that has no is-a relation with the object, 
But generics provide the way to find this kind of error when you complie the code.