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:
Example001:

List list=new ArrayList();
list.add("coderbd");
String str=(String) list.get(0);
System.out.println("list[0]::"+str);

But check the example bellow that will throw ClassCastException.

Example002:

List list=new ArrayList();
list.add("coderbd");
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:

Example003:

List<String> list=new ArrayList<>();
	list.add("CoderBD");
	list.add("coders");
	list.add("Property");
	int i=0;
	for(String s : list){
	//no need casting
	i++;
	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.

Example004:

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

public class Example004 {

public static void main(String...strings) {
List<Integer> intList=new ArrayList<>();
intList.add(100);
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