GotchaDifficulty: Advanced1 min

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:

java
class Box<T> {
    private T[] items = new T[10];
}
text
Box.java:2: error: generic array creation

Creating 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.

What else erasure makes impossible on a type parameter
WrittenWhy 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 TNothing to test against
T.classThere 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.

java
class Box<T> {
    private final List<T> items = new ArrayList<>();
}