ArrayList collection
The bottom layer of ArrayList is an Object array whose length can be dynamically adjusted.
There is a size field that records the length of the array.
The default length of the array is 10, and an empty array is also prepared.
ArrayList has a parent class and implements multiple interfaces such as List (there is no method in RandomAccess, Cloneable, java.io.Serializable interface)
Create without parameters :
ArrayList list = new ArrayList();
In JDK1.7, when an ArrayList object is created using the parameterless constructor, the default underlying array length is 10.
In JDK1.8, when an ArrayList object is created using the parameterless construction method, the default underlying array length is 0. When an element is added for the first time, the capacity must be expanded.
Execute the code:
list.add(20);
The specific implementation of expansion:
Expand the capacity by 50% each time, and compare it again after the expansion.
Assign the length of the array to oldCapacity
int oldCapacity = elementData.length;
New array capacity = 1.5 times the old array length. oldCapacity >> 1 is equivalent to dividing by 2
int newCapacity = oldCapacity + (oldCapacity >> 1);
If the new array capacity newCapacity is less than the minimum capacity minCapacity required by the incoming parameter, then the new array capacity is subject to the incoming capacity parameter.
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
If the new array capacity newCapacity is greater than the maximum number of elements that the array can hold MAX_ARRAY_SIZE 2^{31}-1-8
, then judge whether the incoming parameter minCapacity is greater than MAX_ARRAY_SIZE, if minCapacity is greater than MAX_ARRAY_SIZE, then newCapacity is equal to Integer.MAX_VALUE, no or newCapacity equal to MAX_ARRAY_SIZE.
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
Other methods:
//1
list.size();
Return size directly:
//2
list.isEmpty();
By judging whether the size is 0, if the length is 0, it is empty:
//3
list.indexOf(20);
Internally, a for loop is used to judge:
//4
list.get(2);
Check if the index is out of range
If it exceeds the range (too large), an IndexOutOfBoundsException
is reported. If the index is negative, a runtime exception is reported.
//5
list.iterator();