Erasure Generic in java
Erasure in Java generics refers to the process by which generic type information is removed during compilation, replacing type parameters with their bounding or erasing them to their leftmost bound. This process is necessary to maintain compatibility with legacy code and to ensure that generics work seamlessly with pre-existing non-generic code.
Table of Contents
Explanation Erasure Generic
1. Compatibility with Legacy Code:
Java generics were introduced in Java 5 (JDK 1.5) as a way to add compile-time type checking and type safety to the language. However, generics needed to be implemented in a way that maintains compatibility with existing code written in earlier versions of Java that did not support generics.
2. Type Erasure
To achieve compatibility with legacy code, Java generics use type erasure, which removes generic type information during compilation. This means that generic type parameters are replaced with their bounding or erased to their leftmost bound, resulting in type-unsafe code at runtime.
3. Runtime Representation
At runtime, generic types are represented as raw types (non-generic types) due to erasure. This allows code compiled with generics to interoperate seamlessly with legacy code that does not use generics.
java
import java.util.ArrayList;
import java.util.List;
public class ErasureExample {
public static void main(String[] args) {
List<String> stringList = new ArrayList<>(); // Generic List<String>
stringList.add("Java"); // Adding a String to the list
// At compile time, the type parameter <String> is erased,
// and the compiled bytecode uses raw type List instead.
// This is because of type erasure.
List rawList = stringList; // Raw List (no generic type)
rawList.add(10); // Adding an Integer to the raw list (unsafe)
// At runtime, the generic type information is erased,
// so both elements (String and Integer) are 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, the type parameter is erased at compile time, and the compiled bytecode uses the raw type List instead. This allows an Integer element to be added to the list, resulting in type-unsafe code. At runtime, the generic type information is erased, leading to a ClassCastException when attempting to cast elements to their expected types.