As part of my intensive Java training I got asked to review the source code of the common collections in the JDK. 

I started by cloning the JDK Mercurial repository and checking the ArrayList implementation, and it’s a surprise to see there is not black magic in the code, is the same code that you or me may create for solving the same problem: create a resizable array with common operations. 

The arraylist has internally an Object array that stores every object added through the constructor or the add, addAll operations. The “black magic” comes when you find the arrays can’t be resized, so how the ArrayLists manages to do this. 

Well, when you call the constructor without a collection to add (the empty constructor) the array is initialized empty. When you use the constructor with a collection will use the Arrays.toArray method to store your collection.

Any time you call the add() method java ensures there is enough space , and grows the array +1 by making a new one, copying the elements of the previous array and adding the new one on the new space (see the code below).

private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}

The maximum length of the ArrayList is the Integer.MAX_VALUE or 2,147,483,647 elements since the list relies on a standard array.  After reaching this size any subsequent try to add elements will result on an out of memory exception.

I will write about the delete, addAll and the basic methods specified on the List interface and how ArrayLists implements them in the next posts.