Card 07/ 09
Erasure Limits: Why You Cannot Write new T[]
A generic class that needs an array of its own type parameter, a compile error, and the collection that replaces the array.
Because type arguments are erased, removed by the compiler once it has checked them, a type parameter T, the placeholder a generic class is written with, does not exist while the program runs. Anything that needs the real type at that moment, such as creating an array of T, is refused by the compiler.
A generic class that wants an array of its own type parameter:
class Box<T> {
private T[] items = new T[10];
}Box.java:2: error: generic array creationCreating an array needs a real type at that moment, because an array carries its element type with it and checks every write against it. With T erased there is nothing to carry.
| Written | Why it is refused |
|---|---|
new T[10] | Array creation needs a type that still exists at runtime |
new T() | There is no class to instantiate |
x instanceof T | Nothing to test against |
T.class | There is no class literal for something erased |
catch (T e) | The handler is matched by type at runtime |
The practical answer is almost always to use a collection instead. List<T> works because a list stores Object references and the compiler inserts the casts, which is exactly what an array cannot do.
class Box<T> {
private final List<T> items = new ArrayList<>();
}← → move through sections and cards