Java collection source code analysis ①----ArrayList

ArrayList collection

The bottom layer of ArrayList is an Object array whose length can be dynamically adjusted.
insert image description here
There is a size field that records the length of the array.
insert image description here

The default length of the array is 10, and an empty array is also prepared.
insert image description here
ArrayList has a parent class and implements multiple interfaces such as List (there is no method in RandomAccess, Cloneable, java.io.Serializable interface)
insert image description here

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.
insert image description here
insert image description here
Execute the code:

list.add(20);

insert image description here
The specific implementation of expansion:
insert image description here
insert image description here
Expand the capacity by 50% each time, and compare it again after the expansion.
insert image description here
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:
insert image description here

//2
list.isEmpty();

By judging whether the size is 0, if the length is 0, it is empty:
insert image description here

//3
list.indexOf(20);

Internally, a for loop is used to judge:
insert image description here

//4
list.get(2);

Check if the index is out of range

insert image description here
If it exceeds the range (too large), an IndexOutOfBoundsException
insert image description here
is reported. If the index is negative, a runtime exception is reported.

//5
list.iterator();

insert image description here

Guess you like

Origin blog.csdn.net/myjess/article/details/119513515