Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)
How does Type Erasure work in Java Generics and what are its runtime implications?
senior LevelCode ExampleTypeScriptSystem Design
In Simple Words:
Type Erasure is the mechanism where the Java compiler enforces type constraints at compile time, but removes (erases) all generic type information when emitting bytecode (.class file). At runtime, generic types like List<String> and List<Integer> are identical: both are simply the raw type List.
Why Type Erasure Exists:
To maintain backward compatibility with legacy Java 1.4 codebases when generics were introduced in Java 5 (2004).
Runtime Limitations Caused by Erasure:
- Cannot instantiate generic types directly:
new T()is illegal. - Cannot create generic arrays:
new T[10]is illegal. - Cannot use primitive types in generics:
List<int>is invalid (must use wrapperList<Integer>). - Cannot check
instanceof List<String>(onlyinstanceof List<?>is allowed).
java
// What you write in Java:
List<String> names = new ArrayList<>();
names.add("Alice");
String first = names.get(0);
// What bytecode actually executes (decompiled equivalent):
List names = new ArrayList();
names.add("Alice");
String first = (String) names.get(0); // Compiler injects automatic cast