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) {
myList.add(“A”);
myList.add(“B”);
myList.add(“C”);
Iterator itr = myList.iterator();
while (itr.hasNext()) {
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) {
myList.add(“A”);
myList.add(“B”);
myList.add(“C”);
myList.add(1);Iterator itr = myList.iterator();
while (itr.hasNext()) {
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) {
myList.add(“A”);
myList.add(“B”);
myList.add(“C”);
myList.add(1); //Compiler Error
Iterator<String> itr = myList.iterator();
while (itr.hasNext()) {
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.
- Top 45 Fresher Java Interview Questions - March 9, 2023
- 25 Free Practice Questions – GCP Certified Professional Cloud Architect - December 3, 2021
- 30 Free Questions – Google Cloud Certified Digital Leader Certification Exam - November 24, 2021
- 4 Types of Google Cloud Support Options for You - November 23, 2021
- APACHE STORM (2.2.0) – A Complete Guide - November 22, 2021
- Data Mining Vs Big Data – Find out the Best Differences - November 18, 2021
- Understanding MapReduce in Hadoop – Know how to get started - November 15, 2021
- What is Data Visualization? - October 22, 2021