Before jdk 1.5 ArrayList class is defined as follows. class ArrayList {
add(Object o) ;
Object get(int index);
– –
}



See the above code . The argument of add() method is Object, hence we can add any type to ArrayList . Due to this, before jdk 5 we are not getting the type safety .

The return type of get() method is Object , hence we should type cast while getting the data from collection.

jdk 5 onwards generic version of ArrayList is declared as follows. class ArrayList<T> {
add(T t) ;
T get(int index);
– –
}

‘T’ will be replaced with provided type at runtime . For example , if you provided String type then ‘T’ will be replaced with String at runtime. See the below example .

ArrayList l = new ArrayList();

For above requirement loaded version of ArrayList is as follows. class ArrayList<String > {
add(String t) ;
String get(int index);
– –
}

See the above example . add() takes String as argument , hence we can add String type of objects only. If we try to add any other type we will get compiler error . So, we sre getting type safety. Similarly , The return type of get() is String , hence we need not to typecast.

Similarly , jdk 5 onwards generic version of HashMap is declared as follows. Two type parameters are passed to HashMap class
class HashMap <K,V> {
– –
}

We can pass any number of type parameter to a class. We can use any letter as type parameter. Classes that are associated with type parameters are called generic classes.