Advertisement
Intermediate Java, Arrays & Multidimensional Arrays

What is array covariance's relationship to generic arrays, and why can't you directly create a generic array like new T[10] or new List<String>[10]?

Short answer

Due to Java's type erasure, generic type information isn't available at runtime, so the JVM couldn't correctly enforce the component type of a genuinely generic array at the point of array creation -- combined with array covariance's already-demonstrated unsoundness…

Save Java mock interview
Advertisement
AModel answer
Due to Java's type erasure, generic type information isn't available at runtime, so the JVM couldn't correctly enforce the component type of a genuinely generic array at the point of array creation -- combined with array covariance's already-demonstrated unsoundness (ArrayStoreException), allowing new T[] or new List<String>[] directly would create even more severe, undetectable type-safety holes, so Java simply disallows this syntax entirely at compile time, requiring workarounds like creating an Object[] and unsafely casting, or preferring a generic-friendly collection like ArrayList<T> instead.
public class Container<T> {
    // private T[] items = new T[10];  // COMPILE ERROR: generic array creation

    @SuppressWarnings("unchecked")
    private T[] items = (T[]) new Object[10];  // common workaround, but unsafe and generates a warning

    // Preferred alternative: just use a List instead
    private List<T> betterItems = new ArrayList<>();
}
Real-world example
A generic container class initially attempts private T[] items = new T[10] and hits a compile error, leading the team to either use the unsafe Object[]-cast workaround (accepting the unchecked warning) or, preferably, refactor to use ArrayList<T> internally instead, sidestepping the entire generic array limitation.
Likely follow-ups
  • Why does the unsafe (T[]) cast workaround still risk a ClassCastException later, and under what circumstances?
  • How does the JDK's own source code (like ArrayList's internal implementation) handle this exact limitation internally?
Related topics