Why does the ArrayList implementation use Object[]?

In Java, creating an array of a generic type is not straightforward.

The simple approach does not compile:

public class Container<E> {

    E[] arr = new E[3]; // ERROR: Cannot create a generic array of E

}

Replace E with Object, and all is well (at the expense of added complexity elsewhere in the container implementation).

There are alternative approaches, but they present a different set of tradeoffs. For an extensive discussion, see How to create a generic array in Java?

Leave a Comment