Type Erasure

Java-Type Erasure

Type Erasure

A generic type in Java is compiled to a single class file. There aren’t separate versions of the generic type for each formal parameterized type. For example, in the following example, Gen<Integer, String> and Gen<Float, Double> aren’t separate versions of the Gen type for each formal parameterized type :

Type Erasure

The implementation of generics utilizes type erasure. In general, here is how type erasure works. When your Java code is compiled, all generic type information is removed (erased). This means replacing type parameters with their bound type, which is Object if no explicit bound is specified, and then applying the appropriate casts (as determined by the type arguments) to maintain type compatibility with the types specified by the type arguments. The compiler also enforces this type compatibility. This approach to generics means that no type parameters exist at run time. The Gen<Integer, String> and Gen<Float, Double> are same version of the Gen type for each formal parameterized type :

Type Erasure

Of course, Gen class doesn’t exist as a separate entity. Looking at the class that now works with references of type Object, you may wonder what the advantage of being able to specify the type parameter is; after all, you can supply a reference to an object of any type for a parameter of type Object. The answer is that the type variable you supply is used by the compiler to ensure compile-time type safety. When you use an object of type Gen in your code, the compiler checks that you use it only to store objects of type Integer and String through the reference of Gen<Integer,String> and any attempt to store objects of other types as an error. When you call methods for an object of type Gen through the reference of Gen<Integer,String>, the compiler ensures that you supply references only of type Integer and String.

Type Erasure

When you program a call to a generic method, the compiler inserts casts when the return type has been erased. For example, consider following the sequence of statements :

Type Erasure

The return type of inst.GetT( ) is Object. The compiler automatically inserts the cast to Integer. This way to compiler ensure type safety. Following example shows how bounded type variables are erased  :

Type Erasure

Program

Type Erasure

Program Source

class Gen<T> {

    private T tary[];
    
    Gen(T tar[]) {
        tary = tar;
    }
    
    void setSpecificElement(int p,T t) {
        tary[p]=t;
    }
    
    T getSpecificElement(int p) {
        return tary[p];
    }
}

public class Javaapp {

    public static void main(String[] args) {

        Gen<Integer> g1 = new Gen<Integer>(new Integer[5]);
        g1.setSpecificElement(0,100);
        g1.setSpecificElement(1,200);
        g1.setSpecificElement(2,300);
        Integer i1 = g1.getSpecificElement(1);
        System.out.println(g1.getSpecificElement(2));
    }
}

Leave a Comment