What Is The Purpose Of Generics In Java ?

The purpose of generics in Java is to offer type safety and to overcome type casting problem.

Type safety can be defined as the concept of holding a correct data by a variable with respect to its type. It means, if a variable is capable of holding string type then it should not allow other types. It prevents type errors, making the compiler efficient to validate types at compile time. Screenshot from 2021 03 07 18 29 08 1

The Generic concept was mainly introduced to make collection type safe. Since, collection framework deals with objects, as a result, it can hold various object types in form of element which doesn’t guarantees type safety.

Here’re two main purpose Of Generics In Java:

– To provide type safety :

In Java, String, arrays are type safe, meaning, no other data is allowed other than itself. for example.

public class TypeSafeExample {
public static void main(String[] args) {
Integer[] rollNumbers = new Integer[20];
rollNumbers[0] = 1;
rollNumbers[1] = 2;
rollNumbers[3] = "3"; // Would throw Incompatible types. Found

System.out.println("Roll Numbers : ");
for (int i = 0; i < rollNumbers.length; i++) {
System.out.println(rollNumbers[i]);
}

}
}

Error :

Incompatible types. Found: 'java.lang.String', required: 'java.lang.Integer'

In above example, an array of integer can hold only integer values, otherwise, it would give compile time error. This is why, array guarantees the elements that it is carrying, always of same type.

However, when Java haven’t purposed the Generic programming, it wasn’t fully type safe.

– To resolve type casting problems :

Type casting is a concept of converting a value from one type to another compatible data type and assigning it to the respective variable on which the casting is performed. Since, collection can consists elements of various types and at the time of retrieval, type casting problem can be occurred which leads to runtime error. Like, below example.

package generics;

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

public class TypeSafeExample {
public static void main(String[] args) {
List rollNumbers = new ArrayList();
rollNumbers.add(1);
rollNumbers.add(2);
rollNumbers.add("3");
System.out.println("Roll Numbers : "+rollNumbers);

// When try to retrive and store to it string type object
for (int i=0; i<rollNumbers.size();i++){
String rollNumber;
rollNumber = (String) rollNumbers.get(i); // Runtime Error class java.lang.Integer cannot be cast to class java.lang.String
System.out.println(rollNumber);
}
}
}
Runtime Error class java.lang.Integer cannot be cast to class java.lang.String

In order to overcome these problem, Java introduced generics concept.

How to Overcome from the problem of Type Safety in Collection?

To make an arraylist to store only same type of element, we need to create arraylist of Integer. As given below.

public class TypeSafeExample {
    public static void main(String[] args) {
        
       List<Integer> rollNumbers =  new ArrayList<Integer>();
        rollNumbers.add(1);
        rollNumbers.add(2);
        rollNumbers.add("3"); // Compile time errror
        System.out.println("Roll Numbers  : "+rollNumbers);
        
    }
}

It is now type safe, since it guarantees the type of elements expected within an ArrayList. Further, It also takes care of type casting problem as it is no longer required to perform by the compiler which was triggering runtime errors previously.

Leave a Reply