ArrayList 的基本结构
ArrayList
的核心是一个动态数组,实际上是一个可调整大小的数组。在 ArrayList
类中,这个数组被声明为:
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
transient Object[] elementData;
这段代码定义了数组的默认初始容量,并声明了一个对象数组 elementData
,这是存储添加到 ArrayList
中的元素的地方。
添加元素
当添加一个元素到 ArrayList
时,它首先检查数组是否足够大,如果不够大,它需要进行扩容。这是通过 ensureCapacityInternal
方法完成的,该方法再调用 grow
方法来确保数组有足够的容量。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDAT