Provide Best Programming Tutorials

Introduction To Generics In Java

Introduction

The key benefit of generics is to enable errors to be detected at compile time rather than at runtime.

A generic class or method permits you to specify allowable types of objects that the class or method can work with. If you attempt to use an incompatible object, the compiler will detect that error.

 

This chapter explains how to define and use generic classes, interfaces, and methods and demonstrates how generics can be used to improve software reliability and readability.

Motivations and Benefits

The motivation for using Java generics is to detect errors at compile time.

Java has allowed you to define generic classes, interfaces, and methods since JDK 1.5. Several interfaces and classes in the Java API were modified using generics. For example, prior to JDK 1.5 the java.lang.The comparable interface was defined as shown in Figure, but since JDK 1.5 it is modified as shown in Figure

Here, <T> represents a formal generic type, which can be replaced later with an actual concrete type. Replacing a generic type is called a generic instantiation. By convention, a single capital letter such as E or T is used to denote a formal generic type.

The figure below shows the version of ArrayList before and after JDK 1.5

So why do we need this change?

Let’s see an example below by given the ArrayList a specific type “String” we can detect the error in compile time instead of Runtime if we add an Integer to this list.

import java.util.ArrayList;

public class GenericsDemo {

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<String>();
        //This works fine because add a String
        arrayList.add("Andrew Programming");
        //This leads an error since add an integer
        // we can detect the error in compile time instead of runtime
        arrayList.add(1);

    }
}

What would happen if we don’t use generics? Let’s see example below as comment demonstrate we cannot detect the error in compile time but in Runtime because lack the help of Generics.

import java.util.ArrayList;

public class BadExample {

    public static void main(String[] args) {
        ArrayList noGenericList = new ArrayList();
        //This ArrayList is supposed to contain String item but infact we add Integer to it
        // which leads to error in Runntime
        noGenericList.add("Andrew Programming");
        noGenericList.add(1);

        for (int i = 0; i < noGenericList.size(); i++) {
            //We want to convent the item in the list to uppercase but there is a Integer in it which will lead error
            String arrayItem = (String) noGenericList.get(i);
            arrayItem.toUpperCase();
        }

    }
}
Exception in thread "main" java.lang.ClassCastException: java.base/java.lang.Integer cannot be cast to java.base/java.lang.String
    at BadExample.main(BadExample.java:11)

Process finished with exit code 1

Leave a Reply

Close Menu