ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的容量能动态增。ArrayList中的操作不是线程安全的!
private static final int DEFAULT_CAPACITY = 10; // 初始容量10
private static final Object[] EMPTY_ELEMENTDATA = {}; // 空实例数组
// 默认大小的空实例数组,在第一次调用ensureCapacityInternal时会初始化长度为10
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
transient Object[] elementData; // 存放元素的数组
private int size; // 数组当前的元素数量
public ArrayList(int initialCapacity) { // 带容量参数的构造方法
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
public ArrayList() { // 不带容量参数则使用默认大小的空实例数组
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) { // 根据索引获取元素
rangeCheck(index); // 校验索引是否越界
return elementData(index); // 直接根据index返回对应位置的元素(底层elementData是个数组)
}
由于底层是数组实现的,先检查下索引是否越界,然后直接返回对应索引位置的元素即可。
public E set(int index, E element) { // 用指定的元素(element)替换指定位置(index)的元素
rangeCheck(index); // 校验索引是否越界
E oldValue = elementData(index); // 根据index获取指定位置的元素
elementData[index] = element; // 用传入的element替换index位置的元素
return oldValue; // 返回index位置原来的元素
}
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return true (as specified by {@link Collection#add})
*/
public boolean add(E e) { // 增加一个元素
ensureCapacityInternal(size + 1); // 将modCount+1,并校验添加元素后是否需要扩容
elementData[size++] = e; // 在数组尾部添加元素,并将size+1
return true;
}
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) { // 将指定的元素(element)插入此列表中的指定位置(index)。将index位置及后面的所有元素(如果有的话)向右移动一个位置
rangeCheckForAdd(index); // 校验索引是否越界
ensureCapacityInternal(size + 1); // 将modCount+1,并校验添加元素后是否需要扩容
System.arraycopy(elementData, index, elementData, index + 1, // 将index位置及之后的所有元素向右移动一个位置(为要添加的元素腾出1个位置)
size - index);
elementData[index] = element; // index位置设置为element元素
size++; // 元素数量+1
}
public E remove(int index) { // 删除列表中index位置的元素,将index位置后面的所有元素向左移一个位置
rangeCheck(index); // 校验索引是否越界
modCount++; // 修改次数+1
E oldValue = elementData(index); // index位置的元素,也就是将要被移除的元素
int numMoved = size - index - 1; // 计算需要移动的元素个数,例如:size为10,index为9,此时numMoved为0,则无需移动元素,因为此时index为9的元素刚好是最后一个元素,直接执行下面的代码,将索引为9的元素赋值为空即可
if (numMoved > 0) // 如果需要移动元素
System.arraycopy(elementData, index+1, elementData, index,
numMoved); // 将index+1位置及之后的所有元素,向左移动一个位置
elementData[--size] = null; // 将size-1,并将size-1位置的元素赋值为空(因为上面将元素左移了,所以size-1位置的元素为重复的,将其移除)
return oldValue; // 返回index位置原来的元素
}
public boolean remove(Object o) { // 如果存在与入参相同的元素,则从该列表中删除指定元素的第一个匹配项。如果列表不包含元素,则不变
if (o == null) { // 如果入参元素为空,则遍历数组查找是否存在元素为空,如果存在则调用fastRemove将该元素移除,并返回true表示移除成功
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else { // 如果入参元素不为空,则遍历数组查找是否存在元素与入参元素使用equals比较返回true,如果存在则调用fastRemove将该元素移除,并返回true表示移除成功
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false; // 不存在目标元素,返回false
}
/*
* Private remove method that skips bounds checking and does not
* return the value removed.
*/
private void fastRemove(int index) { // 私有方法,供上面的remove方法调用,直接删除掉index位置的元素
modCount++; // 修改次数+1
int numMoved = size - index - 1; // 计算需要移动的元素个数,例如:size为10,index为9,此时numMoved为0,则无需移动元素,因为此时index为9的元素刚好是最后一个元素,直接执行下面的代码,将索引为9的元素赋值为空即可
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved); // 将index+1位置及之后的所有元素,向左移动一个位置
elementData[--size] = null; // 将size-1,并将size-1位置的元素赋值为空(因为上面将元素左移了,所以size-1位置的元素为重复的,将其移除)
}
检查索引是否越界,将modCount+1,拿到索引位置index的原元素。
计算需要移动的元素个数。
如果需要移动,将index+1位置及之后的所有元素,向左移动一个位置。
将size-1位置的元素赋值为空(因为上面将元素左移了,所以size-1位置的元素为重复的,将其移除)。
/**
* Removes all of the elements from this list. The list will
* be empty after this call returns.
*/
public void clear() { // 删除此列表中的所有元素。
modCount++; // 修改次数+1
// clear to let GC do its work
for (int i = 0; i < size; i++) // 遍历数组将所有元素清空
elementData[i] = null;
size = 0; // 元素数量赋0
}
add方法在添加元素之前会先调用ensureCapacityInternal方法,主要是有两个目的:1.如果没初始化则进行初始化;2.校验添加元素后是否需要扩容。
private void ensureCapacityInternal(int minCapacity) {
// 校验当前数组是否为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,
// 如果是则将minCapacity设为DEFAULT_CAPACITY,
// 主要是给DEFAULTCAPACITY_EMPTY_ELEMENTDATA设置初始容量
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++; // 修改次数+1
// 如果添加该元素后的大小超过数组大小,则进行扩容
if (minCapacity - elementData.length > 0)
grow(minCapacity); // 进行扩容
}
// 数组允许的最大长度
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) { // 数组扩容
// overflow-conscious code
int oldCapacity = elementData.length; // 原来的容量
int newCapacity = oldCapacity + (oldCapacity >> 1); // 新容量 = 老容量 + 老容量 / 2
if (newCapacity - minCapacity < 0) // 如果新容量比minCapacity小,
newCapacity = minCapacity; // 则将新容量设为minCapacity,兼容初始化情况
if (newCapacity - MAX_ARRAY_SIZE > 0) // 如果新容量比最大允许容量大,
newCapacity = hugeCapacity(minCapacity); // 则调用hugeCapacity方法设置一个合适的容量
// 将原数组元素拷贝到一个容量为newCapacity的新数组(使用System.arraycopy),
// 并且将elementData设置为新数组
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError(); // 越界
// 如果minCapacity大于MAX_ARRAY_SIZE,则返回Integer.MAX_VALUE,否则返回MAX_ARRAY_SIZE
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
ensureCapacityInternal(int minCapacity):此方法就是为默认大小的空实例数组DEFAULTCAPACITY_EMPTY_ELEMENTDATA而写的,判断数组是否为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,如果是则将minCapacity设置为DEFAULT_CAPACITY。
ensureExplicitCapacity(int minCapacity):将modCount+1,并校验minCapacity是否大于当前数组的容量,如果大于则调用grow方法进行扩容。
将数组新容量设置为老容量的1.5倍。
两个if判断,第一个是对DEFAULTCAPACITY_EMPTY_ELEMENTDATA初始化的兼容,第二个是对超过MAX_ARRAY_SIZE的兼容。
调用Arrays.copyOf方法创建长度为newCapacity的新数组,并将老数组的数据复制给新数组,并将elementData赋值为新数组。