Card 07/ 09
All 9 cards
GotchaDifficulty: Advanced1 min
Why You Cannot Write new T[]
A generic class that needs an array of its own type parameter. The line looks unremarkable and the compiler refuses it outright.
class Box<T> {
private T[] items = new T[10];
}Box.java:2: error: generic array creationT is gone by the time the program runs, and creating an array needs a real type at that moment — an array carries its element type with it and checks every write against it. 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<>();
}