Generics in Java

[ad_1]

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();
vc.add("Pakistan");
String s=(String)vc.get(0);       -- "Required Type Cast"

Generics Example

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




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

[ad_2]

Leave a Comment