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);
}
ArrayList public constructor - "Constructs an empty list with an initial capacity of ten" - where? [duplicate] Bookmark this question.
If the capacity passed is equal to 0(initialCapacity==0) then an empty Arraylist will be created.
Default initial capacity of ArrayList is 10. java.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With