Skip to main content
Generics · Topic 7 of 7

Type erasure

Definition​

Type erasure means generic type arguments exist only at compile time. At run time List<String> and List<Integer> are both just List, so you cannot ask a list what type it holds.

Example code​

Two different lists, the same class at run time

import java.util.ArrayList;
import java.util.List;

class Demo {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
List<Integer> integers = new ArrayList<>();
System.out.println(strings.getClass() == integers.getClass()); // true: the type arguments are gone

// Because of erasure, a raw type can sneak the wrong type in...
@SuppressWarnings({"unchecked", "rawtypes"})
List<String> sneaky = (List) integers;
integers.add(42);
try {
String s = sneaky.get(0); // ...and the cast fails here, at run time
} catch (ClassCastException e) {
System.out.println("ClassCastException: " + e.getMessage().substring(0, 30) + "...");
}
}
}

// Output:
// true
// ClassCastException: class java.lang.Integer cannot...

Finished this page? Track your progress (saved only in your browser).