Learnitweb

What is the benefit of Generics in Collections Framework?

In Java, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

Following are the benefits of using generics over non-generic code:

1. Stronger type checks at compile time

Generics allow us to provide the type of objects a collection can contain. So, if you try to add an element which is not of that type it throws compile time error. This avoids ClassCastException at runtime. Fixing compile-time errors is easier than fixing runtime errors.

2. Type casting is not required

Generics make code clean since we don’t need to use casting and instanceof operator. It also adds up to runtime benefit because the bytecode instructions that do type checking are not generated.
The following code snippet without generics requires casting:

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0); // type casting

Using generics, the code does not require casting:

List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);   // no type casting required

3. Generics helps to write generic algorithms

Generics allow programmers to write algorithms that can work on different type of objects and are also type safe.