Lesson · Generics
Type erasure: the types the compiler throws away
16 min readType Erasure
Generics are a compile-time promise: the compiler checks every <...>, then erases it. T becomes its bound, casts are re-inserted at use sites, and Box<String> and Box<Integer> turn out to be one class.
Two lists, one class
Guess before reading on: does the class object of a List<String> remember the String?
List<String> words = new ArrayList<>(); List<Integer> numbers = new ArrayList<>(); System.out.println(words.getClass() == numbers.getClass()); // true
The answer is true, and words.getClass() prints class java.util.ArrayList. The type arguments are gone at run time — every rule in this lesson follows from that one fact.
What the compiler keeps and what it drops
The compiler checks the generics it sees, then throws the type arguments away and patches the uses:
// you write // the runtime works with Box<String> box = new Box<>("hi"); Box box = new Box("hi"); // T is gone String s = box.get(); String s = (String) box.get(); // cast re-inserted
- Erase to the bound: a type parameter disappears — plain
<T>erases toObject;<T extends Number>erases toNumber. - Casts re-inserted at uses: every read from a generic container is compiled with a hidden cast — which is why the source needs none.
- The checks stay compile-time:
words.add(42)is rejected while you type, but nothing about the running ArrayList says "strings only".
Name what it is: erasure is the compiler keeping the promise in your source while leaving no trace of it in the class file's behavior.
Erasure curtain · flip between the two worlds
flip the switchclass Box<T> {
T value;
T get() { return value; }
}
String s = box.get(); // no cast in sight
And the class itself is shared
Because of that, these are refused at compile time
Everything on that list follows from one fact: the text inside <…> never reaches the JVM.
The four things you cannot do
Each impossibility is erasure showing through — there is no runtime type to work with:
| You try to write | The compiler says | Why |
|---|---|---|
new T[3] | error: generic array creation | arrays know their element type at runtime; T does not exist there |
list instanceof List<String> | error: cannot be safely cast to List<String> | the check needs a runtime type — inside <...> there is none |
new T() | error: unexpected type (required: class, found: type parameter T) | not every T can promise a no-argument constructor |
two overloads m(List<String>) and m(List<Integer>) | error: name clash: m(List<Integer>) and m(List<String>) have the same erasure | both signatures erase to m(List) — one method, two names needed |
What you can do instead
When a body really needs the type at runtime, the caller still has it — so ask for it:
- Arrays: pass the component type and let the array be created for you:
(T[]) Array.newInstance(type, n)— or returnList<T>and skip arrays. - Instances: pass
Class<T>and calltype.getDeclaredConstructor().newInstance(). - `instanceof`:
list instanceof List<?>is allowed — the unbounded wildcard erases cleanly; then cast, proving the unchecked warning safe in a comment. - Overloads: rename one —
parseInts(List<Integer>)andparseStrings(List<String>). Erasure has ended the tie; the names must too.
The type travels in values, not in syntax. Class<String> token is a value a caller can hand you; <String> inside List<String> is a note the compiler erases.
Heap pollution: the warning that travels
A raw type opens one door back into the pre-generics world, and the compiler marks it with a warning:
List raw = new ArrayList(); raw.add("hello"); List<String> polluted = raw; // warning: unchecked assignment raw.add(42); // nothing checks the raw list String boom = polluted.get(1); // ClassCastException — at the read, not at the add
- Assigning a raw list to
List<String>is an unchecked conversion: the compiler warns —required: List<String>, found: List— because it cannot verify the contents. - The failure arrives at the read:
class java.lang.Integer cannot be cast to class java.lang.String— produced by the cast the compiler re-inserted atget. - That is heap pollution: a
List<String>variable pointing at a list holding an Integer — the type promise broken while every line compiled. - House rule: treat every unchecked warning as an error in review; if you must suppress, prove the safety next to it.
The exception is far from the crime. The add(42) is silent; the crash is at the first read that trusted the declared type.
The erasure playbook
Working with generics knowing they vanish:
- Design with generics — the compiler checks everything it can, and that is most things.
- At runtime there is only the erased class: no
instanceof List<String>, nonew T[], nonew T(), no overloads that differ only by type argument. - When the body truly needs the type, pass it in: a
Class<T>token or a component type for the array. - Treat every unchecked warning as a bug report — heap pollution throws far from its cause.
The boundary is the point. Everything that must be checked at runtime — casting, array creation, instance tests — needs a runtime type; erasure says you must bring one.
Generics are a compile-time promise; the JVM was never told
The compiler checks every <...> and then erases it: T becomes its bound (or Object), casts are re-inserted at use sites, and Box<String> and Box<Integer> share one class. Everything you cannot do — new T[], instanceof List<String>, overloads differing only by type argument — follows from that single fact. Unchecked warnings mark the exact places a raw type punched a hole in the promise.
Interview angles
What is type erasure?+
Generics exist for the compiler: it checks the type arguments, then removes them from the compiled code — replacing them with their bound and re-inserting casts where values are read.
The class file has no record of String in List<String>: the list is a plain ArrayList, the field is Object (or the bound), and reads carry a hidden cast. One generic class serves every type argument at runtime.
Common misconception: That the runtime keeps the type arguments hidden somewhere — it does not; only the compiler ever saw them.
Follow-up: So what does words.getClass() == numbers.getClass() return?
Why can't you write new T[3] or use instanceof List<String>?+
Neither has a runtime type to work with: T is erased, and List<String> is not a runtime type at all.
Arrays remember their component type at runtime (that is why storing a String into an Integer[] throws), and instanceof asks the runtime about a type — generics are gone by then. The allowed forms ask less: instanceof List<?> and (List<String>) list with an acknowledged warning.
Common misconception: That these are temporary language limitations someone will lift — they follow directly from erasure and are permanent by design.
Follow-up: What do you pass when a method truly needs the type?
Where does the cast in `String s = box.get();` come from? There is none in the source.+
The compiler inserts it. Erasure turned get() into a method returning Object, so every use re-asserts the type the source promised.
That inserted cast is also where ClassCastException comes from in generic code: normally it can never fail, because every write was checked at compile time — unless a raw path smuggled in a wrong element (heap pollution).
Common misconception: That generic reads are free — each one carries a cast; the JIT usually eliminates it, but the guarantee comes from compile-time checking, not from the cast.
Follow-up: When does a List<String> actually throw ClassCastException?
What is heap pollution, and how does the compiler warn you?+
A generic variable pointing at storage that violates its type — usually via a raw type or unchecked cast. The compiler flags the mixing point with an unchecked warning.
The warning appears where the two meet (unchecked conversion, required: List<String>, found: List), but the exception appears at the next read, get(1), because that is where the re-inserted cast runs. The two locations are the story: the crime is where the types mixed; the crash is where someone trusted the promise.
Common misconception: That unchecked warnings are noise to suppress — each one marks a place where a ClassCastException may be waiting.
Follow-up: How do you fix it — at the warning line or somewhere else?
Can a generic class have a static field of type T?+
No — static context cannot see the class's type parameter: the compiler reports that the type variable cannot be referenced from a static context.
The deeper reason is erasure's logical companion: there is only one Box class for every Box<String>, Box<Integer> and Box<Whatever>. A static field would be shared by all of them, so it cannot have a type that differs per user.
Common misconception: That each Box<String> and Box<Integer> has its own statics — they share the single class's statics.
Follow-up: What does that tell you about static caches inside generic classes?