Generics and type erasure
Mid-level Frequently asked 6 min
On this page
The question
What is type erasure in Java generics?
30-second answer
Generics exist for the compiler. javac checks every use of a type argument, then erases it: a List<String> becomes a plain List whose methods take and return Object, and javac inserts a cast where a value is read. At runtime a List<String> and a List<Integer> share one class, which kept generic code compatible with code written before Java 5.
Understand it
From List<String> to a plain List
Step by stepThe source declares List<String> names. The type argument String tells the compiler what the list may hold.
View as text
The drawing shows a pipeline from the .java file to javac, the .class file and the JVM, above three lines of code: List<String> names = new ArrayList<>(), names.add("Ann") and String s = names.get(0).
The source declares List<String> names. The type argument String tells the compiler what the list may hold.
javac checks every call against String: add("Ann") compiles and add(42) is a compile error. The check happens before the program ever runs. The line names.add(42) appears with a mark saying int is a compile error, while add("Ann") is marked as compiling.
Compiling erases the type arguments. The .class file holds a plain List whose add() takes an Object and whose get() returns one. The type arguments <String> and <> are struck out of the first line, and comments show add(Object) and get() returning Object.
Where the value is read as a String, javac inserts a (String) cast after get(0). The bytecode runs it as a checkcast instruction. The last line becomes String s = (String) names.get(0), with the cast highlighted.
At runtime no list object records its type argument: a List<String> and a List<Integer> built as ArrayLists share one class, so their getClass() values are equal. Two boxes, List<String> and List<Integer>, each created with new ArrayList<>(), both point at one box, ArrayList.class, marked as the same class.
The drawing shows a pipeline from the .java file to javac, the .class file and the JVM, above three lines of code: List<String> names = new ArrayList<>(), names.add("Ann") and String s = names.get(0).
The source declares List<String> names. The type argument String tells the compiler what the list may hold.
javac checks every call against String: add("Ann") compiles and add(42) is a compile error. The check happens before the program ever runs. The line names.add(42) appears with a mark saying int is a compile error, while add("Ann") is marked as compiling.
Compiling erases the type arguments. The .class file holds a plain List whose add() takes an Object and whose get() returns one. The type arguments <String> and <> are struck out of the first line, and comments show add(Object) and get() returning Object.
Where the value is read as a String, javac inserts a (String) cast after get(0). The bytecode runs it as a checkcast instruction. The last line becomes String s = (String) names.get(0), with the cast highlighted.
At runtime no list object records its type argument: a List<String> and a List<Integer> built as ArrayLists share one class, so their getClass() values are equal. Two boxes, List<String> and List<Integer>, each created with new ArrayList<>(), both point at one box, ArrayList.class, marked as the same class.
Takeaway: Generics are checked by the compiler, then erased. A cast inserted where a value is read keeps the code type-safe, and at runtime every List shares one class.
Pick the wildcard for each parameter
BuildGive each method parameter the list type that fits. A list the method reads from produces values; a list it writes to consumes them.
Drag a piece, or select it and then select a place.
- Empty
- Empty
- Empty
- Empty
- Empty
View as text
Five method parameters each need a list type. The drawing shows each method beside its parameter, with an arrow from the list into the method where it reads and from the method into the list where it writes. Give each method parameter the list type that fits. A list the method reads from produces values; a list it writes to consumes them.
The answers are: sum(list) reads Numbers from the list, so it takes List<? extends Number>, a producer. fill(list) adds Integers to the list, so it takes List<? super Integer>, a consumer. In copy(dest, src), the list it reads from is List<? extends T>, the source, and the list it writes to is List<? super T>, the destination. swapFirst(list) reads and writes Integers, so it takes List<Integer> with no wildcard.
Producer extends, consumer super: ? extends where the method reads, ? super where it writes, and no wildcard where it does both.
Five method parameters each need a list type. The drawing shows each method beside its parameter, with an arrow from the list into the method where it reads and from the method into the list where it writes. Give each method parameter the list type that fits. A list the method reads from produces values; a list it writes to consumes them.
The answers are: sum(list) reads Numbers from the list, so it takes List<? extends Number>, a producer. fill(list) adds Integers to the list, so it takes List<? super Integer>, a consumer. In copy(dest, src), the list it reads from is List<? extends T>, the source, and the list it writes to is List<? super T>, the destination. swapFirst(list) reads and writes Integers, so it takes List<Integer> with no wildcard.
Producer extends, consumer super: ? extends where the method reads, ? super where it writes, and no wildcard where it does both.
Takeaway: Producer extends, consumer super: a list the method reads from takes ? extends, a list it writes to takes ? super, and a list it does both with takes the exact type.
In code
List<String> names = new ArrayList<>();
names.add("Ann");
// names.add(42); compile error: int cannot be converted to String
String s = names.get(0); // javac inserts a (String) cast here
Wrong List raw = names; // raw type: the compiler stops checking
raw.add(42); // unchecked warning, but it runs
String t = names.get(1); // ClassCastException at the inserted cast
List<Integer> ids = new ArrayList<>();
System.out.println(names.getClass() == ids.getClass()); // truestatic double sum(List<? extends Number> list) { // reads Numbers
double total = 0;
for (Number n : list) total += n.doubleValue();
return total;
}
static void fill(List<? super Integer> list) { // writes Integers
for (int i = 1; i <= 3; i++) list.add(i);
}
static <T> void copy(List<? super T> dest, List<? extends T> src) {
for (T item : src) dest.add(item);
}
List<Number> numbers = new ArrayList<>();
fill(numbers); // [1, 2, 3]
copy(numbers, List.of(2.5)); // [1, 2, 3, 2.5]
System.out.println(sum(numbers)); // 8.5static <T extends Comparable<? super T>> T max(List<? extends T> items) {
T best = items.get(0);
for (T item : items) if (item.compareTo(best) > 0) best = item;
return best;
}
Integer top = max(List.of(3, 9, 4)); // 9
String last = max(List.of("b", "a")); // "b"Solve it
Why can’t you write new T[16], and how does a generic container store its items?
A candidate writes a generic Box<T> backed by T[] items = new T[16] and gets “generic array creation”. Explain the
error and give two ways to build the container.
- Recall erasure. At runtime
Tis gone and becomesObject, so the JVM (Java Virtual Machine) does not know which element type to create. - Recall that arrays are reified. An array checks every store against its element type at runtime, so it must be created with a real class. Erasure leaves none.
- Option one: ask the caller. Take an
IntFunction<T[]>such asString[]::new, asCollection.toArraydoes. The array is a realString[]. - Option two: hide an
Object[]. StoreObject[]and cast on the way out, asArrayListdoes. Never return the array itself. - Check. Both compile without raw types; the unchecked cast stays private, with one
@SuppressWarningson it.
class Box<T> {
private final T[] items;
Box(IntFunction<T[]> newArray, int size) { items = newArray.apply(size); } // a real T[] from the caller
void set(int i, T item) { items[i] = item; }
T get(int i) { return items[i]; }
}
Box<String> names = new Box<>(String[]::new, 16);
class Stack<T> {
private Object[] items = new Object[16]; // what ArrayList does internally
private int size;
void push(T item) { items[size++] = item; }
@SuppressWarnings("unchecked") T pop() { return (T) items[--size]; } // safe: only T goes in
}How to answer
- The compiler rejects
names.add(42)on aList<String>, so the type check happens before the program runs. - Erasure replaces a type parameter with its bound:
TbecomesObject, andT extends NumberbecomesNumber. - javac inserts a
checkcastwhere a generic value is read, as inString s = names.get(0). new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass()istrue.- Erasure is why
new T(),new T[n]ando instanceof List<String>on anObjectdo not compile.
Common mistakes
- Saying the JVM checks the type argument on every
add; at runtime only the inserted casts check anything. - Saying every trace of the type argument is gone; field and method signatures keep it for reflection, objects do not.
Follow-up questions
What is the difference between ? extends and ? super, and what does PECS mean?
PECS stands for producer extends, consumer super. A List<? extends Number> produces values: every element reads as a Number, but you cannot add one, because the list might be a List<Double>. A List<? super Integer> consumes values: you can add Integers, but reading gives only Object. A list the method both reads and writes takes the exact type, with no wildcard.
List<? extends Number> l; l.add(1)is a compile error;nullis the only value you can add.- Reading a
List<? super Integer>givesObject:Integer x = l.get(0)does not compile. Collections.copy(List<? super T> dest, List<? extends T> src)follows the rule: it reads the source and writes the destination.- Wildcards widen an API:
sum(List<? extends Number>)accepts aList<Integer>and aList<Double>.
See it in the infographic: Pick the wildcard for each parameter
Why can't you write new T() inside a generic class or method?
Because T is erased. The bytecode does not record which class T stands for, so the compiler cannot emit a constructor call, and new T() fails with "unexpected type". For the same reason new T[n] is a "generic array creation" error. Pass the knowledge in instead: a Supplier<T> such as StringBuilder::new, or a Class<T> whose constructor you call through reflection.
- A
Supplier<T>is the type-safe fix, andmake(StringBuilder::new)returns aStringBuilder. - A
Class<T>token also works:type.getDeclaredConstructor().newInstance(), at the cost of checked reflection exceptions. - For arrays, use a
List<T>or take anIntFunction<T[]>, asCollection.toArray(String[]::new)does.
static <T> T make(Supplier<T> factory) {
return factory.get();
}
StringBuilder sb = make(StringBuilder::new); See it in the infographic: From List<String> to a plain List
What is a raw type, and why should you avoid it?
A raw type is a generic type used without type arguments, such as List instead of List<String>. It exists so code written before generics still compiles. The compiler stops checking it and gives only an unchecked warning, so a raw List can put an Integer into a List<String>. The error surfaces later, as a ClassCastException at the cast inserted where the value is read.
- By default javac prints only a summary note;
-Xlint:rawtypesand-Xlint:uncheckedwarn on each line. - The failure is far from the bug, because the
addsucceeds and a latergetthrows. - Use
List<?>for a list of unknown type, which you can read asObjectbut cannot add to exceptnull.
List<String> names = new ArrayList<>();
List raw = names; // raw type
raw.add(42); // unchecked warning, runs
String s = names.get(0); // ClassCastException See it in the infographic: From List<String> to a plain List
Why is a List<Integer> not a List<Number>?
If it were, code holding it as a List<Number> could add a Double, and the List<Integer> would then hold a Double. So generics are invariant and the assignment is a compile error. Arrays are covariant instead: Object[] arr = new Integer[1] compiles, and storing a String in it throws ArrayStoreException. Accept both with List<? extends Number>.
What is a bridge method?
A synthetic method javac adds so that overriding still works after erasure. When Box implements Comparable<Box>, its compareTo(Box) does not match the erased compareTo(Object), so javac generates a compareTo(Object) that casts its argument to Box and calls compareTo(Box). Reflection reports it with isBridge() returning true.
Check yourself
Show answers
- true: Correct. Erasure leaves one ArrayList class, whatever the type argument.
- false: Incorrect. Type arguments exist only for the compiler, so both lists share a class.
- It does not compile: Incorrect. Comparing two Class objects with == compiles.
Show answers
- List<? extends Number>: Correct. The list is a producer, every element reads as a Number, and both lists qualify.
- List<? super Number>: Incorrect. That accepts a List<Number> or a List<Object>, not a List<Integer>.
- List<Number>: Incorrect. Generics are invariant, so a List<Integer> is not a List<Number>.