Why does the ArrayList implementation use Object[]?

arraylist, generics, java

Solution

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?

Problem

In Java `ArrayList<E>` implementation base on a array of objects. Can anybody explain me why implementation of `ArrayList<E>` uses array `Object[]` for data storage instead of `E[]`? What the benefit of using `Object[]`?

Original source

Related problems