Video in progress
Why can't you write new T[], and what are the ways to create a generic array correctly?
Because of erasure, T is unknown at runtime, but an array has to know its element type at runtime. The way out is to pass a Class<T> or an IntFunction<T[]>, or to keep an Object[] inside and return a List to the outside.
📖 Answer
Arrays are reified: a String[] knows its type at runtime and throws ArrayStoreException if a wrong element is written. Generics are erased. Because these two models collide, new T[n] is forbidden.
The common "trick" and what it leads to:
@SuppressWarnings("unchecked")
T[] arr = (T[]) new Object[10]; // works inside
public T[] toArray() { return arr; } // outside, a cast to String[] -> CCE
Ways that work:
// 1) A Class token
T[] arr = (T[]) Array.newInstance(type, n);
// 2) A generator: the JDK does it this way too
<A> A[] toArray(IntFunction<A[]> gen) { ... }
String[] s = list.toArray(String[]::new);
// 3) A List instead of an array
private final List<T> items = new ArrayList<>();
ArrayList keeps an Object[] elementData inside and never hands it out as a T[]: follow its example. If the array is only an internal detail, Object[] plus a cast is fine; in an external API, use a List or a generator.
Sign up to mark studied questions and save your progress.