Purpose of Generics:
To make object type checking for java collection at compile time.
Ex: List<E> list = new ArrayList<E>();
E denoted the type.
List<Integer> list = new ArrayList<Integer>();
Pros :
Ø It provide abstraction over types
Class,interface,method can be parametrized by Types.
Ø It makes type safe code possible
To avoid ClassCastException at runtime.
Ø It provides readability.
Ø Inheritance relationship between generic classes themselves still exists.
Ex: List<Integer> list = new ArrayList<Integer>();
Ø Entries in a collection maintain inheritance relationship.
Ex: ArrayList<Number> list = new ArrayList<Number>();
list.add(new Integer(10));
list.add(new Long(20L));
Ø Use of Wildcard type arugument.
Collection<?> means collection of unknown type.
Ex: void printValues(Collection<?> coll){
for(Object o:coll){
s.o.p(o);
}
}
Collection<String> collStrings = new ArrayList<String>();
printValues(collStrings);
Collection<Integer> collIntegers = new LinkedList<Integer>();
printValues(collIntegers);
Ø Use of Bounded wildcard.(bound the unknown type to be a subtype of another type)
Ex: void printValues(Collection<? extends Number> coll ){
}
Collection<Integer> collIntegers = new LinkedList<Integer>();
printValues(collIntegers);
Collection<Long> collLongs = new LinkedList< Long >();
printValues(collLongs);
Ø Type erasure – generic type information are removed in the resulting byte-code after compilation. So it becomes a RawType.
Ex: List<Integer> list; will converted to List list;
Ø Creating own generic class.
Public class Car<S,I>{
S s;
I i;
public Car(S s,I i){
s=s;
i=i;
}
}
Car<String,Integer> car1= new Car<String,Integer>(“RollsRoyce”,new Integer(007));
Cons:
Ø It does not allow subtyping because ClassCastException might occur at runtime.
Ex: ArrayList<Object> list = new ArrayList<Integer>();
Ø There is no inheritance relationship between type arguments of a generic class.