What is benefit of Generics in Collections Framework

What is benefit of Generics in Collections Framework

Generics in java enable types to be parameterized when defining classes, interfaces and methods. Its like familiar formal parameters used in when declare methods; type parameters provide way for us to re-use same code with different inputs parameters. Difference is that inputs to the formal parameters are values, while inputs to type parameters are types.

In java generics have many benefits over non-generic code:

  • Stronger type check at code compiles time.

Java compiler applies strong type checking to the generic code and issue errors if code violates type safety or not. Fixing compile time errors are easier than fixing runtime errors, which could be difficult to find.

  • Elimination of casting.

Below code snippet without generics requires casting:

package com.javahonk.genericstest;

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

public class GenericsTest {

	public static void main(String[] args) {

		List list = new ArrayList();
		list.add("Java Honk");
		// casting done for String
		String s = (String) list.get(0);

	}

}

 

When re-written using generics, code does not requires casting:

package com.javahonk.genericstest;

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

public class GenericsTest {

	public static void main(String[] args) {

		List<String> list = new ArrayList<String>();
		list.add("Java Honk");
		String s = list.get(0);
		System.out.println(s);

	}

}

 

It enables us to implement generic algorithms.

By using generics,  we could implements generic algorithms that could work on different types of collections, could be customized, and are also type safe and easier to read.

 

Check out all interview questions

Leave a Reply

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

I am not Robot *