Type erasure
Type erasure is how Java implements generics: the compiler checks your type arguments, then removes them, so the running program sees plain Object with casts inserted. A list of strings and a list of integers are the same class at runtime.
Detailed Explanation
Generics arrived in Java 5, sixteen years after the first release, into an ecosystem full of compiled libraries that knew nothing about them. The designers had two options. Change the JVM so it understands generic types, and break every existing class file. Or keep the JVM exactly as it was and do all the work in the compiler. They chose the second, and erasure is the consequence.
Here is what the compiler actually does. It type-checks your source using the full generic information. Then it rewrites List<String> to List, rewrites an unbounded T to Object, rewrites a bounded T extends Comparable<T> to Comparable, and inserts a cast wherever a generic value is read. The bytecode that comes out could have been written by a Java 1.4 programmer by hand. That is the point: old code and new code call each other freely, and the migration cost was near zero.
The trade is that type arguments do not exist at runtime. new ArrayList<String>().getClass() and new ArrayList<Integer>().getClass() return the same Class object. There is no way to ask a list what it holds, because the list does not know.
That single fact produces a checklist of restrictions worth memorising for interviews:
new T()andnew T[10]are illegal. There is no class to instantiate at runtime.instanceof List<String>is illegal. Onlyinstanceof List<?>compiles.- Two overloads that differ only in type argument, such as
f(List<String>)andf(List<Integer>), clash. After erasure they are the same method. - A class cannot implement
Comparable<String>andComparable<Integer>at once. - Static fields are shared across all parameterisations. There is no separate
Box<String>.count.
Erasure also introduces two artefacts you may meet while debugging. The first is heap pollution: if raw types or unchecked casts let a wrong value into a collection, nothing complains at insertion time, and the failure surfaces later at the synthetic cast the compiler inserted at the read site. The stack trace points at code that is innocent. The second is bridge methods, synthetic methods the compiler generates so that overriding still works after erasure changes a signature; they show up in reflection output and in stack traces and confuse people who did not write them.
Not everything is erased. Generic signatures are preserved in class file metadata for the compiler and for tools, which is why an IDE can still see that a library method returns Map<String, User>. Frameworks exploit this through the "super type token" trick, where you subclass a generic type anonymously so the type argument becomes part of the class's own signature; Jackson's TypeReference and Spring's ParameterizedTypeReference both work this way.
The costs are the ones already listed, plus the big one: no primitive specialisation. C++ templates and Rust generics generate separate machine code per type, so a vector of integers stores raw integers. Java cannot, so List<Integer> boxes. Project Valhalla is the long-running effort to fix that.
Code Examples
import java.util.ArrayList;
import java.util.List;
public class ErasureDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List<Integer> ages = new ArrayList<>();
// The type argument is gone. Both objects have the same runtime class.
System.out.println(names.getClass() == ages.getClass()); // prints: true
System.out.println(names.getClass().getName()); // prints: java.util.ArrayList
// Only the unbounded form compiles; instanceof cannot see type arguments.
Object maybeList = names;
System.out.println(maybeList instanceof List<?>); // prints: true
// System.out.println(maybeList instanceof List<String>); // does not compile
}
}import java.util.ArrayList;
import java.util.List;
class HeapPollution {
public static void main(String[] args) {
List<String> tokens = new ArrayList<>();
// A raw type switches generic checking off for this reference.
List raw = tokens;
raw.add(42); // compiles with an unchecked warning; no runtime check exists
System.out.println(tokens.size()); // prints: 1
// The lie is only discovered here, at the cast the compiler inserted
// for us on the read side:
// String first = tokens.get(0); // throws ClassCastException
}
}Common Gotchas
Overloads that erase to the same signature do not compile
`void save(List<User>)` and `void save(List<Order>)` are the same method after erasure. Rename one, or take a `Class<T>` argument to distinguish them.
Unchecked warnings are deferred exceptions
every `@SuppressWarnings("unchecked")` you add moves a possible `ClassCastException` to a random later line. Suppress it only on a single statement you have personally proved safe, never on a whole class.
Generic arrays are why `toArray` takes an argument
`List.toArray(new String[0])` passes a real runtime type because the list itself cannot manufacture one. Arrays keep their component type at runtime; generics do not.
The signature survives in metadata
reflection can recover the declared type argument of a field or a method return through `getGenericType`, which is how JSON libraries deserialise into `List<User>` even though the object itself is type-blind.