Why will we use Generics?

There are many benefits if you use generics in your code:

• It strongly checks type at compile time and provides compile time type safety.
• It has removed ClassCastException that is common senrio at java collection classes.
• Without genetics, it is needed to use class cast and if it passes compiler test, but it shows runtime error or ClassCastException
• A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
• It eliminates type casting. Look at the example bellow:

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

But check the example bellow that will throw ClassCastException.


List list=new ArrayList();
list.add(new Integer(10));// it seems to be OKAY	
for(Object obj : list){
String str=(String) obj;//throws ClassCastException
System.out.println("str as String by casting obj::"+str);
  • When re-written to use generics, the code does not require casting:


List<String> list=new ArrayList<>();
	int i=0;
	for(String s : list){
	//no need casting
	System.out.println("list:: "+i+" :"+s);

It checks at Compile-Time, so problem will catch at compile runtime. And as a result, we can avoid runtime error.


import java.util.ArrayList;
import java.util.List;

public class Example004 {

public static void main(String...strings) {
List<Integer> intList=new ArrayList<>();
intList.add("Coderbd");// Here will produce compile time error
  • It enables coders to use generic algorithms and so coders can implement generic algorithms that are type safe, customized and easier to read.

Leave a Reply