The concept of Java Generics was introduced in JDK 5 to deal with type-safe objects. Before generics, we can store any type of objects in collection which result in lots of casting errors. Now Java generics, forces the programmer to store specific type of objects in collections.
Advantages of Java Generics
- Type Safety – Only single type of object is allowed.
- Type casting not required – It helps to eliminate casting.
- Compile time checking – Stronger type check at compile time, so the problem will not occur at runtime.
- Generics make programmers to implement generic algorithms.
Elimination of casts
The following code snippet without generics requires casting:
List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0);
When re-written to use generics, the code does not require casting:
List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // no cast