Java集合:ArrayList详解

时间:2022-03-14 17:52:03

概述

ArrayList是我们日常中最长用的集合之一,在使用列表时,除非特殊情况,我们一般都会选择使用ArrayList,本文就ArrayList的几个主要方法主要介绍,并结合几个图片来介绍几个重要操作。


基础属性

/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10; // 初始容量10

/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {}; // 用于空实例的共享空数组实例

/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; // 用于默认大小(10)空实例的共享空数组实例,此处没有初始化,在第一次调用ensureCapacityInternal时会初始化为长度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. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // 存放元素的数组

/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size; // 数组当前的元素数量

一些基本属性,参考下图理解。

Java集合:ArrayList详解


get方法

@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是个数组)
}
很简单,由于底层是数组实现的,先检查下索引是否越界,然后直接返回对应索引位置的元素即可。

set方法

public E set(int index, E element) {    // 用指定的元素(element)替换指定位置(index)的元素
rangeCheck(index); // 校验索引是否越界

E oldValue = elementData(index); // 根据index获取指定位置的元素
elementData[index] = element; // 用传入的element替换index位置的元素
return oldValue; // 返回index位置原来的元素
}

  1. 校验索引是否越界
  2. 根据index获取指定位置的元素
  3. 用传入的element替换index位置的元素
  4. 返回index位置原来的元素

add方法

/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (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
}
add(E e):

  1. 调用ensureCapacityInternal方法,将modCount+1,并校验添加元素后是否需要扩容。
  2. 在elementData数组尾部添加元素即可(size位置)。

add(int index, E element):

  1. 检查索引是否越界,再调用ensureCapacityInternal方法,将modCount+1,并校验添加元素后是否需要扩容。
  2. 将index位置及之后的所有元素向右移动一个位置(为要添加的元素腾出1个位置)。
  3. 将index位置设置为element元素,将size+1。

add(int index, E element)的过程如下图所示

Java集合:ArrayList详解


remove方法

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位置的元素为重复的,将其移除)
}
remove(int  index):

  1. 检查索引是否越界,将modCount+1,拿到索引位置index的原元素。
  2. 计算需要移动的元素个数。
  3. 如果需要移动,将index+1位置及之后的所有元素,向左移动一个位置。
  4. 将size-1位置的元素赋值为空(因为上面将元素左移了,所以size-1位置的元素为重复的,将其移除)。

remove(Object o):

  1. 如果入参元素为空,则遍历数组查找是否存在元素为空,如果存在则调用fastRemove将该元素移除,并返回true表示移除成功。
  2. 如果入参元素不为空,则遍历数组查找是否存在元素与入参元素使用equals比较返回true,如果存在则调用fastRemove将该元素移除,并返回true表示移除成功。
  3. 否则,不存在目标元素,则返回false。
fastRemove(int index):跟remove(int index)类似
  1. 将modCount+1,并计算需要移动的元素个数。
  2. 如果需要移动,将index+1位置及之后的所有元素,向左移动一个位置。
  3. 将size-1位置的元素赋值为空(因为上面将元素左移了,所以size-1位置的元素为重复的,将其移除)。

remove(int  index)方法的过程如下图所示。
Java集合:ArrayList详解

clear方法

/**
* 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
}
遍历数组将所有元素清空即可。

ensureCapacityInternal方法

private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { // 校验是否为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,如果是则将minCapacity设为DEFAULT_CAPACITY(主要是对初始化后添加的第一个元素起效果,会给DEFAULTCAPACITY_EMPTY_ELEMENTDATA设置初始容量)
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}

ensureExplicitCapacity(minCapacity);
}

private void ensureExplicitCapacity(int minCapacity) {
modCount++; // 修改次数+1

// overflow-conscious code
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小,则将新容量设为minCapacity
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0) // 如果新容量比最大允许容量大,则调用hugeCapacity方法设置一个合适的容量
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity); // 将原数组元素拷贝到一个容量为newCapacity的新数组(使用System.arraycopy),并且elementData设置为新数组
}

private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ? // 如果minCapacity大于MAX_ARRAY_SIZE,则返回Integer.MAX_VALUE,否则返回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方法进行扩容。
grow(int minCapacity):
  1. 将数组新容量设置为老容量的1.5倍。
  2. 两个if判断,第一个是对DEFAULTCAPACITY_EMPTY_ELEMENTDATA初始化的兼容,第二个是对超过MAX_ARRAY_SIZE的兼容。
  3. 调用Arrays.copyOf方法创建长度为newCapacity的新数组,并将老数组的数据复制给新数组,并将elementData赋值为新数组。
grow(int minCapacity)的过程如下图所示。
Java集合:ArrayList详解

ArrayList和LinkedList比较

LinkedList详解可以看我的另一篇文章:Java集合:LinkedList详解

  1. ArrayList底层基于动态数组实现,LinkedList底层基于链表实现
  2. 对于随机访问(get/set方法),ArrayList通过index直接定位到数组对应位置的节点,而LinkedList需要从头结点或尾节点开始遍历,直到寻找到目标节点,因此在效率上ArrayList优于LinkedList
  3. 对于插入和删除(add/remove方法),ArrayList需要移动目标节点后面的节点(使用System.arraycopy方法移动节点),而LinkedList只需修改目标节点前后节点的next或prev属性即可,因此在效率上LinkedList优于ArrayList。


参考

ArrayList源码(JDK 1.8)