Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList public constructor - "Constructs an empty list with an initial capacity of ten" - where? [duplicate]

Tags:

java

arraylist

Be aware, it is not a duplicate of Why start an ArrayList with an initial capacity?

Looking into the source code of the java.util.ArrayList class, starting from at least java 1.8 I see the following code:

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

Where

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

Though the javadoc officially states:

Constructs an empty list with an initial capacity of ten.

I outline: ...an initial capacity of ten. Where is this ten?

Am I completely mad and missing something, or there is simply a javadoc bug here?

UPD: How it looked like prior java 1.8:

public ArrayList(int initialCapacity) {
    super();
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    this.elementData = new Object[initialCapacity];
}

/**
 * Constructs an empty list with an initial capacity of ten.
 */
public ArrayList() {
    this(10);
}
like image 947
Andremoniy Avatar asked Dec 13 '18 13:12

Andremoniy


People also ask

Which class can create an empty list the capacity of the list is initialize to 10?

ArrayList public constructor - "Constructs an empty list with an initial capacity of ten" - where? [duplicate] Bookmark this question.

What might an initial capacity be passed to the constructor of an empty dynamic array?

If the capacity passed is equal to 0(initialCapacity==0) then an empty Arraylist will be created.

What is the initial capacity of the ArrayList al When this class is executed?

Default initial capacity of ArrayList is 10. java.


1 Answers

This is an optimization. The developers decided to initialize the ArrayList with an empty backing array, and lazily create a non-empty backing array only when you start adding elements to the List.

When you add the first element (by calling add), it calls

ensureCapacityInternal(size + 1);

which checks if elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA, and if so, sets the capacity to

minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);

DEFAULT_CAPACITY is 10.

like image 102
Eran Avatar answered Sep 18 '22 12:09

Eran