Advantages of Java Generics

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

  1. Type Safety – Only single type of object is allowed.
  2. Type casting not required – It helps to eliminate casting.
  3. Compile time checking – Stronger type check at compile time, so the problem will not occur at runtime.
  4. Generics make programmers to implement generic algorithms.

Elimination of casts
The following code snippet without generics requires casting:

List list = new ArrayList();
String s = (String) list.get(0);

When re-written to use generics, the code does not require casting:

List<String> list = new ArrayList<String>();
String s = list.get(0); // no cast

Java Professional with rich experience in Java development.
– Designing and developing high-volume, low-latency applications with high-availability and performance.
– Writing well designed, robust and efficient code.

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By :