Generics in Java


Generics introduced in J2SE 5.0. Generics introduced for Collections. Collection store Objects and any type of object can be store in collection. When a stored object pulled back from collection it required to cast that object. Compiler does not check the type at compile time. Type Cast can be failed at runtime.Generics allow particular(Unique but similar) types of object to save in Collections. If wrong type of object added in Collections the program will fail at compile time. Generics provides Type Safety, No Types Cast Required.

Earlier Example of Collection

Vector vc=new Vector();
String s=(String)vc.get(0);       -- "Required Type Cast"

Generics Example

Vector<String> vc=new Vector<String>();
String country=vc.get(0);         -- "No Type Cast"

List<String> list=new ArrayList<String>();
String country=list.get(0);         -- "No Type Cast"


Leave a Comment