How does ArrayList work?

Internally an ArrayList uses an Object[].

As you add items to an ArrayList, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.

Now, there is more room left, and the new element is added in the next empty space.

Since people really like the source code:

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * The capacity of the ArrayList is the length of this array buffer.
 */
private transient Object[] elementData;

Straight out of the JDK.

Leave a Comment