Type erasure
A type argument exists only while the compiler is reading the source. In the class file, Box<String> is Box, its field is an Object and its accessor returns an Object with a cast inserted by the compiler. That removal is erasure, and it explains four things that otherwise look arbitrary: why the class of two lists is the same, why an array of a type parameter cannot be created, why two overloads clash, and why a Class object is how a program carries a type into run time.
What the compiler erases
Each type parameter is replaced by its bound, or by Object when it has none, and each use of the parameter gets a cast where a specific type is needed. The compiler also writes a bridge method when a subclass fixes a parameter, which is how the override still dispatches without the parameter at run time. None of it is visible in the source; all of it is visible in javap, and lesson 055 showed that tool on a record.
Erasure was chosen in 2004 so that generic code could call old code and the other way round: a List<String> is a List at run time, so a method written before generics still accepts it. The price is that the type argument is not available at run time, and every rule below follows from that price.
Two lists, one class
The program asks two lists of different type arguments for their classes and compares them:
import java.util.ArrayList;
import java.util.List;
public class Erased {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
System.out.println(names.getClass().getName());
System.out.println(numbers.getClass().getName());
System.out.println(names.getClass() == numbers.getClass());
Object raw = names;
List<?> view = (List<?>) raw;
System.out.println(view.size());
}
}
javac -Xlint:all Erased.java
java Erased
java.util.ArrayList
java.util.ArrayList
true
0
Both names are java.util.ArrayList, and the two getClass calls return the same object, because there is one class. The argument was checked at the two add calls that do not exist here, and then forgotten. A method that takes a List at run time cannot tell a list of strings from a list of numbers.
Why new T[] is refused
An array knows its element type at run time: storing a String into a Integer[] throws ArrayStoreException. A type parameter has no run-time type, so the JVM cannot build an array that checks its elements, and the compiler refuses the creation:
public class NoArray {
public static void main(String[] args) {
String[] strings = make(3);
System.out.println(strings.length);
}
static <T> T[] make(int size) {
return new T[size];
}
}
javac -Xlint:all NoArray.java
NoArray.java:8: error: generic array creation
return new T[size];
^
1 error
The error is two words and points at the new. The answer is a Class token or an Object[] plus a cast, which is what a collection does internally and why a collection is the right container for generic elements. The next two sections show both halves of that.
The name clash
Overloading is decided by the parameter types, and after erasure both methods below take a List. The compiler sees two methods with one signature and refuses the second:
import java.util.List;
public class Clash {
public static void main(String[] args) {
System.out.println(describe(List.of("a")));
}
static String describe(List<String> values) {
return "strings " + values.size();
}
static String describe(List<Integer> values) {
return "ints " + values.size();
}
}
javac -Xlint:all Clash.java
Clash.java:12: error: name clash: describe(List<Integer>) and describe(List<String>) have the same erasure
static String describe(List<Integer> values) {
^
1 error
The message names both methods and the reason in one line. The fix is a different name, a different parameter count, or one method with a List<?> and a check inside; a cast inside is exactly the unchecked operation lesson 065 warned about.
Class<T> as a token
A Class<T> object is the type as a value: it survives erasure because it is an object, its type argument says what it is the class of, and reflection can build an array from it. This is how a generic method creates an array it is not allowed to create with new:
import java.lang.reflect.Array;
import java.util.Arrays;
public class Token {
public static void main(String[] args) {
String[] words = make(String.class, 3, "x");
Integer[] numbers = make(Integer.class, 2, 7);
System.out.println(Arrays.toString(words));
System.out.println(Arrays.toString(numbers));
System.out.println(words.getClass().getSimpleName());
}
@SuppressWarnings("unchecked")
static <T> T[] make(Class<T> type, int size, T value) {
T[] array = (T[]) Array.newInstance(type, size);
Arrays.fill(array, value);
return array;
}
}
javac -Xlint:all Token.java
java Token
[x, x, x]
[7, 7]
String[]
Array.newInstance is told the element class, so the array it returns really is a String[], which the last line proves. The cast is unchecked, because the compiler cannot prove that the array matches T; it is correct here because the token and the value agree, and the suppression says that a person checked.
What erasure means for a program
Four rules follow, and each one has appeared above. A type argument is not available at run time, so a program that needs the type passes a Class token, or a factory object, or keeps the type in a field. An array of a type parameter cannot be created, so a generic container holds an Object[] and casts on read, or the caller supplies the array. Two methods that differ only in their type arguments are one method, so the compiler refuses the second. And an instanceof List<String> is not legal, because there is no List<String> at run time; the instanceof of lesson 059 tests a raw type and the element type must be checked by hand.
Erasure is also why an old class still works with a new list: a Vector and an ArrayList meet at List, the type the bytecode holds. Lesson 065 read that compatibility from the other side, as the reason the old classes survived.
Exercises
- Print List.class.getName() and compare it with the two names of Erased.java.
- Change NoArray to take a Class<T> and build the array as Token does.
- Rename one of the two methods of Clash and run the program.
- Write new Object[3] with a cast to T[] and explain the warning it gives.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the compiler do to a type parameter in the class file?
Answer
Replaces it with its bound, or with Object, and inserts casts
That replacement is erasure, and it is why the argument is not available at run time.
-
Why are two lists of different type arguments one class at run time?
Answer
The type argument is erased, so both are ArrayList
There is one ArrayList class, and the argument existed only in the source.
-
What does this program print?
import java.util.ArrayList; import java.util.List; public class Q1 { public static void main(String[] args) { List<String> a = new ArrayList<>(); List<Integer> b = new ArrayList<>(); System.out.println(a.getClass() == b.getClass()); } }Answer
true
Both variables hold an ArrayList, and the type arguments are erased.
-
What is the first line of the compiler output for this program?
public class Q2 { public static void main(String[] args) { System.out.println(make(2).length); } static <T> T[] make(int n) { return new T[n]; } }Answer
error: generic array creation
The creation of an array of a type parameter is refused by the compiler.
-
What is the first line of the compiler output for this program?
import java.util.List; public class Q3 { public static void main(String[] args) { System.out.println(size(List.of(1))); } static int size(List<String> values) { return values.size(); } static int size(List<Integer> values) { return values.size(); } }Answer
error: name clash: size(List<Integer>) and size(List<String>) have the same erasure
Both parameters erase to List, so the two methods have one signature.
-
What does this program print?
import java.lang.reflect.Array; import java.util.Arrays; public class Q4 { public static void main(String[] args) { Integer[] numbers = make(Integer.class, 2, 5); System.out.println(Arrays.toString(numbers)); System.out.println(numbers.getClass().getSimpleName()); } @SuppressWarnings("unchecked") static <T> T[] make(Class<T> type, int size, T value) { T[] array = (T[]) Array.newInstance(type, size); Arrays.fill(array, value); return array; } }Answer
[5, 5] then Integer[]
The token makes a real Integer array, and fill puts the value in both slots.
-
Why is
instanceof List<String>not allowed?Answer
There is no List<String> at run time, only List
The test would have to check an argument that erasure removed.
-
What does
Class<T>carry that a type argument cannot?Answer
The type as a run-time object, which survives erasure
A Class object exists at run time, so a factory or a reflective call can use it.
-
What does
@SuppressWarnings("unchecked")say?Answer
A person checked the cast that the compiler cannot verify
The annotation removes a warning that the compiler cannot prove either way, and it is a statement of trust.
-
Why did Java choose erasure in 2004?
Answer
So generic code and code written before generics could call each other
Compatibility with the existing collections and libraries was the deciding constraint.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev