Java implements generics through a process called type erasure. This means that generic type information is removed (erased) by the compiler before the bytecode is generated. As a result, generic types are not available at runtime—they exist only at compile time for type checking and safety.
What Is Type Erasure?
Type erasure is Java’s technique to maintain backward compatibility with older versions (pre-Java 5) by removing generic type parameters during compilation.
Example
List<String> list = new ArrayList<>();
list.add("Java");
String s = list.get(0);
Code language: PHP (php)
After type erasure, it becomes
List list = new ArrayList(); // Raw type
list.add("Java");
String s = (String) list.get(0); // Explicit cast
Code language: PHP (php)
Why Java Uses Type Erasure
-
Backward compatibility: Older code without generics must still work.
-
Simpler bytecode: All generic type information is removed, avoiding overhead.
-
Type safety at compile time: Generics catch errors before runtime, even though the types are erased afterward.
3. How Type Erasure Works
When the compiler sees a generic type, it:
-
Replaces it with its upper bound (usually
Object
if not specified). -
Inserts type casts where needed.
-
Removes the actual generic type from the compiled
.class
file.
Example:
class Box<T> {
private T item;
public void set(T item) { this.item = item; }
public T get() { return item; }
}
Code language: JavaScript (javascript)
After erasure:
class Box {
private Object item;
public void set(Object item) { this.item = item; }
public Object get() { return item; }
}
Code language: JavaScript (javascript)
Type Erasure is a core concept in Java generics that ensures compile-time type safety without affecting runtime performance or backward compatibility. However, it comes with trade-offs, such as the inability to use instanceof
or create generic arrays. Understanding how type erasure works helps you write more robust and type-safe Java code.