Warning. Type erasure

[comp1110-4D]

Java generics are implemented via type erasure: at runtime, the type parameter T is erased to Object, so the expression new T[n] is illegal: the Java runtime has no idea what T is. Any generic class that needs an array internally must therefore either allocate an Object[] and cast values out of it appropriately, or somehow get an object that knows what to create:

// Inside a generic class with type parameter T: private Object[] data; // must be Object[], not T[] @Override public T[] coming(Function<Integer, T[]> arrayCreator) { T[] result = arrayCreator.apply(count); int i=0; while(i < count) { result[i] = (T)data[i]; i = i + 1; } return result; }

The casts inserted here work in practice as long as only values of type T are inserted — and this should be maintained through encapsulation — but it is a genuine limitation of how Java implements generics.

bars magnifying-glass caret-down plus minus arrow-right xmark