Youssef Youssef - 15 days ago 5
Java Question

ArrayList capacity when creating a new ArrayList

I know there are lots of discussions about the ArrayList capacity out there, but still I can't find my answer though, which is specific to a comment in the ArrayList class.

Looking at the ArrayList class in Java (7), I came across this part of the code:

/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}


The comment above is stating that the capacity will be 10 when using this constructor. But this does not look correct as: this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; is just setting elementData to be an empty array with size 0.

So my question is, what is the capacity actually going to be when using this constructor and before adding any element to the ArrayList? is it 0 (thats what I think) or 10 as the comment states?

Answer

What happens is when ArrayList is created using the ArrayList() constructor then the data is assigned to this placeholder, for the purpose of "lazy initialization"

/**
 * Shared empty array instance used for default sized empty instances. We
 * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
 * first element is added.
 */
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

As soon as you try to add an item, private method ensureCapacityInternal() will be called, which will jump to DEFAULT_CAPACITY, which is 10...

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }

    ensureExplicitCapacity(minCapacity);
}

If you use the ArrayList<>(int n) constructor then internal data is setup as an Object[] of size n immediately.

Comments