JAVA GENERICS – BASIC USAGE

Generics is an important feature of Java which was introduced in the version 1.5. Generics allows us to create generalized collections and provides a way of type safety at compile time. Generalized collections means any collection from java.util package which only accepts a particular type. For example, an ArrayList of String objects can be considered as a generalized list. With the help of Generics, we can ensure that our ArrayListor of any other collection only accepts any specific type of objects. This safety check is done at compile time.

Before the introduction of Generics (Java 1.4 and previous versions), developers had to depend on type casting to retrieve elements, if the element retrieved happened to be a different type, a runtime exception is thrown. Type casting is error prone and also the code is difficult to understand and maintain. Generics helps to avoid these problems by enabling the type safety at compile time.

The concept of Generics can be best described using an example. Consider the following sample Java program, which creates an ArrayList and inserts three String objects to it.

package learning;

import java.util.ArrayList;
import java.util.Iterator;

public class GenericsTest {

public static void main(String[ ] args) {

ArrayList myList = new ArrayList();
myList.add(“A”);
myList.add(“B”);
myList.add(“C”);
Iterator itr = myList.iterator();
while (itr.hasNext()) {
String myStr = (String)itr.next();
System.out.println(myStr);

}

}

}

The above program works fine when we print the ArrayList and it prints values [A, B, C]. However when we try to insert an object into our ArrayList (myList in this case), we’ll get runtime error. For example, if we try to insert an integer to myList as shown in the below complete program.

package learning;

import java.util.ArrayList;
import java.util.Iterator;

public class GenericsTest {

public static void main(String[ ] args) {

ArrayList myList = new ArrayList();
myList.add(“A”);
myList.add(“B”);
myList.add(“C”);
myList.add(1);Iterator itr = myList.iterator();
while (itr.hasNext()) {
String myStr = (String)itr.next();
System.out.println(myStr);

}

}

}

As you can see, we have added an integer to the myList. When we run this code, we will get the following runtime exception.

Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

This is due to the fact that, an integer cannot be cast to a String. Since we are doing type casting in the while loop to String, we are assuming that whatever value comes from myList is a String. The exception occurred because we received an integer and we did a type cast from integer to String which is illegal.

Generics solves this problem at compile time itself. The following revised program makes use of Generics to implement type safe ArrayListwhich accepts String objects only.

package learning;

import java.util.ArrayList;
import java.util.Iterator;

public class GenericsTest {

public static void main(String[ ] args) {

ArrayList myList = new ArrayList();
myList.add(“A”);
myList.add(“B”);
myList.add(“C”);
myList.add(1); //Compiler Error
Iterator<String> itr = myList.iterator();
while (itr.hasNext()) {
String myStr = (String)itr.next();
System.out.println(myStr);

}

}

}
As you can see, the above program uses Generics to create an ArrayList which only accepts Strings. When we try to insert an integer to the same list, we’ll get compiler error. So, the type safety check is performed at compile time itself rather than at runtime. Also, we specified type safety to the Iterator as well. We do not need explicit type casting when we call itr.next() to get the next element in the list. Since the outcome of the list is always going to be String (or any other type we specified using Generics notation) we can safely retrieve elements without additional burden of type casting.

In this article, we learned about Generics and basic usage. In the next few articles, we’ll dig deeper into Generics concept and learn more advanced usage of Generics.

Learn more about Generics codes and examples in Whizlabs OCPJP 6 Training Course.

About Aditi Malhotra

Aditi Malhotra is the Content Marketing Manager at Whizlabs. Having a Master in Journalism and Mass Communication, she helps businesses stop playing around with Content Marketing and start seeing tangible ROI. A writer by day and a reader by night, she is a fine blend of both reality and fantasy. Apart from her professional commitments, she is also endearing to publish a book authored by her very soon.
Scroll to Top