What is type erasure in Java Generics?

What is type erasure in Java Generics?

Type erasure in Java generics refers to the process by which generic type information is removed or erased during compilation. This process is necessary to maintain backward compatibility with pre-existing non-generic code and to ensure that generics work seamlessly with legacy code.

type erasure

Explanation

1. Compile-Time Only: Generics in Java provide compile-time type checking and type safety. However, at runtime, the generic type information is erased or removed, and all generic type parameters are replaced with their bounding or erased to their leftmost bound.

2. Raw Types: After type erasure, generic types are represented as raw types, which are non-generic types. This means that all generic type information, including parameterized types, type arguments, and type variables, is removed from the compiled bytecode.

3. Compatibility with Legacy Code: Type erasure allows code written with generics to interoperate seamlessly with legacy code that does not use generics. It ensures that generic code can be compiled into bytecode that is compatible with older versions of Java that do not support generics.

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

public class TypeErasureExample {
    public static void main(String[] args) {
        // Create a generic list of strings
        List<String> stringList = new ArrayList<>();
        stringList.add("Java");
        
        // At compile time, generic type information is erased
        // The compiled bytecode uses the raw type List instead of List<String>
        List rawList = stringList; // Raw List (no generic type)
        
        // Add an integer to the raw list (unsafe operation)
        rawList.add(10);
        
        // At runtime, the generic type information is erased
        // so both strings and integers can be stored in the list
        for (Object obj : stringList) {
            String str = (String) obj; // ClassCastException at runtime
            System.out.println(str);
        }
    }
}

In this example, a generic List is created, and a string element is added to it. However, due to type erasure, at compile time, the generic type information is erased, and the compiled bytecode uses the raw type List instead of List. This allows an Integer element to be added to the list, resulting in type-unsafe code. At runtime, when attempting to iterate over the list, a ClassCastException occurs when trying to cast elements to their expected types, demonstrating the effects of type erasure.

Homepage

Readmore