What is type erasure in Java generics?
Type erasure is the mechanism by which the Java compiler removes all generic type parameters from the bytecode it produces. The resulting .class file contains no information about the specific type arguments used — only the erasure (the raw type or the bound) remains. This was a deliberate compatibility decision: generics were added to Java 5 without requiring changes to the JVM or breaking pre-existing bytecode.
During compilation, the compiler replaces each unbounded type parameter T with Object, and each bounded type parameter <T extends Comparable<T>> with Comparable. All casts necessary for type safety are inserted by the compiler at call sites. The programmer never writes these casts; the compiler guarantees they are correct based on the compile-time generic types.
The practical consequences of type erasure:
1. No runtime type information: List<String> and List<Integer> are the same type at runtime — both are just List. You cannot write obj instanceof List<String> or cast to List<String> safely if the source is untyped. Unchecked casts produce an unchecked cast warning rather than a compile error, because the compiler knows it cannot verify the runtime type.
2. No generic arrays: new T[10] is illegal. The JVM creates the array with the erased type at runtime, which would be Object[], defeating type safety.
3. No instantiation of type parameters: new T() is illegal because T is not known at runtime. Workarounds involve passing a Class<T> token or a Supplier<T> factory.
4. No overloading by generic parameter: void process(List<String> l) and void process(List<Integer> l) have the same erasure (void process(List l)) and cannot coexist.
5. Bridge methods: when a subclass overrides a generic method with a specific type, the compiler generates a synthetic bridge method with the erased signature that delegates to the typed override, maintaining polymorphism correctly.
Heap pollution is a related concept: a variable of parameterized type can refer to an object that is not of that type, producing a ClassCastException at an unexpected location far from the problematic cast.
Correctly explains that type parameters are replaced with Object or bounds in bytecode, and names at least two practical consequences (instanceof, array creation, overloading).
Covers the historical compatibility rationale, all four practical constraints (instanceof, new T[], overloading, no runtime reification), bridge methods, and heap pollution.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment