The Plain Picture#
The "SHOES ONLY" labels are checked at the warehouse door — and then peeled off. Inside the warehouse, every box looks the same. The door check was enough to keep things correct, but inside, nobody can tell a "shoes" box from a "books" box.
The Real Name#
Type erasure: the compiler uses generic types to check your code, then erases them — replacing T with Object (or with its bound,
like Comparable) and inserting casts where needed. The bytecode and the running program have no generic type information. Java did this
in 2004 so that new generic code and old non-generic code (and old JVMs' class files) would work together.
Proof:
List<String> ls = new ArrayList<>();
List<Integer> li = new ArrayList<>();
System.out.println("same class at runtime: " + (ls.getClass() == li.getClass()));
// same class at runtime: trueUnder the Hood — the limits erasure causes (interview favourites)#
Because T doesn't exist at run time, you cannot:
| You can't | Why | What to do |
|---|---|---|
new T() | the JVM doesn't know what T is | pass in a factory, e.g. Supplier<T> (Modern Java) |
new T[10] or new List<String>[10] | arrays need their exact element type at run time | use List<T>, or cast an Object[] carefully |
x instanceof List<String> | only List exists at run time | x instanceof List<?> |
List<int> | erased T becomes Object, which can't hold a primitive | List<Integer> (boxing) or a primitive array |
overload f(List<String>) and f(List<Integer>) | both erase to f(List) — identical | use different method names |
static field of type T | there's one static copy shared by Box<String> and Box<Integer> | — |
Arrays are different — they keep their type at run time (they're "reified"), and they're covariant: a String[] is an Object[]. That
allows a bug generics prevent:
Object[] arr = new String[1]; // allowed: arrays are covariant
arr[0] = 42; // compiles... but the array knows it's a String[] and refuses at run time:
// ArrayStoreException: java.lang.IntegerThe generic equivalent doesn't even compile (Ch 10).
Check yourself
4 questionsWhat is type erasure, and why did Java choose it?
Show answerHide answer
Generic types are checked at compile time and then removed from the bytecode; chosen for backward compatibility with pre-generics code and JVMs.
Why can't you write new T()?
Show answerHide answer
At run time the actual type T isn't known, so there's nothing to construct.
Why are List<String> and List<Integer> the same class at run time?
Show answerHide answer
Type arguments are erased; both are just ArrayList.
Why is Object[] arr = new String[1]; arr[0] = 42; a runtime error rather than a compile error?
Show answerHide answer
Arrays are covariant, so the assignment compiles; but arrays keep their real element type at run time and reject the Integer with an ArrayStoreException.