1. ArrayList 简介
ArrayList 是由数组实现的List。
我们来看他的继承关系:
ArrayList 实现了 Cloneable 接口,可以被克隆。
ArrayList 实现了 Serializable 接口,可以被序列化。
ArrayList 实现了 List 接口,拥有 List 接口的基础操作。
ArrayList 实现了 RandomAccess 接口,可以实现随机访问。
2. 属性
/**
1. 默认初始化容量.
*/
private static final int DEFAULT_CAPACITY = 10;
/**
2. 用于参数为空时的空数组.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
3. 用于默认大小的空实例的共享空数组。
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
4. 存储元素的数据缓冲区,ArrayList的容量就是该数组的长度。在添加第一个元素时,
会将空的ArrayList扩展为默认初始化容量。使用 transient 修饰是为了不序列化该字段。
*/
transient Object[] elementData;
// non-private to simplify nested class access
/**
5. ArrayList 包含的元素个数。
*/
private int size;
3. 构造函数
ArrayList(int initialCapacity)
/**
* 构造具有初始化容量的空列表。
*
* @param initialCapacity 初始化容量
* @throws IllegalArgumentException 初始化容量为负时
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
//如果initialCapacity > 0,新建一个对应初始化容量的数组。
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
//如果initialCapacity = 0,使用 EMPTY_ELEMENTDATA 数组。
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
ArrayList()
/**
* 无参构造函数,构造初始化容量为10的List.
*/
public ArrayList() {
//使用 DEFAULTCAPACITY_EMPTY_ELEMENTDATA 数组,再添加第一个元素时扩容为10。
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
4. 方法
E get(int index)
/**
* 取对应下标元素
*
* @param index
* @return 对应元素
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
//检查下标是否越界
rangeCheck(index);
//返回对应下表元素
return elementData(index);
}
/**
* 越界检查
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
E set(int index, E element)
/**
* 替换对应下标元素
*
* @param index
* @param element
* @return 之前在对应位置的元素
* @throws IndexOutOfBoundsException
*/
public E set(int index, E element) {
//检查下标是否越界
rangeCheck(index);
//取出旧值
E oldValue = elementData(index);
//重新赋值
elementData[index] = element;
return oldValue;
}
boolean add(E e)
/**
* 将元素添加到末尾
*
* @param e 要添加的元素
* @return 添加完成true,否则false
*/
public boolean add(E e) {
//检查元素个数+1是否需要扩容
ensureCapacityInternal(size + 1);
//赋值
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
//确保容量
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//如果集合为空,默认容量和最小容量取较大的
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
// 修改次数加1,说明这是一个支持fail-fast的集合
modCount++;
// 如果最小容量 > 列表长度
if (minCapacity - elementData.length > 0)
//扩容
grow(minCapacity);
}
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
//新容量扩容为旧容量的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
//如果新容量 < 最小容量,将新容量修改为最小需要的容量
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//如果新容量超过最大容量,仍使用最大容量
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 创建新数组,将老数组拷贝到新数组
elementData = Arrays.copyOf(elementData, newCapacity);
}
add(int index, E element)
/**
* 将元素插入到指定位置,如果该位置元素后面有元素,将后面元素右移。
*
* @param index 插入的位置
* @param element 插入的元素
* @throws IndexOutOfBoundsException 下标越界异常
*/
public void add(int index, E element) {
//检查下标是否越界
rangeCheckForAdd(index);
//检查元素个数+1是否需要扩容
ensureCapacityInternal(size + 1);
//将index后面的元素右移一位
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//插入到index位置
elementData[index] = element;
//大小+1。
size++;
}
E remove(int index)
/**
* 移除对应下标元素,将后续元素左移
*
* @param index
* @return 被移除的元素
* @throws IndexOutOfBoundsException
*/
public E remove(int index) {
//检查下标是否越界
rangeCheck(index);
// 修改次数加1,说明这是一个支持fail-fast的集合
modCount++;
//取旧值
E oldValue = elementData(index);
//需要移动元素的个数
int numMoved = size - index - 1;
if (numMoved > 0)
//如果需要移动元素个数大于0,左移
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//末尾元素置空,方便GC回收
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
boolean remove(Object o)
/**
* 移除第一次出现的指定元素
*
* @param o
* @return 存在返回true,不存在返回false
*/
public boolean remove(Object o) {
if (o == null) {
//遍历列表,找空元素
for (int index = 0; index < size; index++)
//元素为空,用==判断
if (elementData[index] == null) {
//找到之后快速删除
fastRemove(index);
return true;
}
} else {
//遍历列表,找非空元素
for (int index = 0; index < size; index++)
//元素非空,用equals判断
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
// 修改次数加1,说明这是一个支持fail-fast的集合
modCount++;
//左移元素
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,numMoved);
//末尾元素置空,方便GC回收
elementData[--size] = null;
}
void clear()
/**
* 移除全部元素
*/
public void clear() {
// 修改次数加1,说明这是一个支持fail-fast的集合
modCount++;
// 置空让GC回收
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
boolean addAll(Collection<? extends E> c)
/**
* 将集合c中元素添加到当前列表
*
* @param c 集合
* @return
* @throws NullPointerException
*/
public boolean addAll(Collection<? extends E> c) {
//集合转数组
Object[] a = c.toArray();
int numNew = a.length;
//检查元素个数+c中元素数是否需要扩容
ensureCapacityInternal(size + numNew);
//将c中元素添加到当前列表末尾
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
boolean addAll(int index, Collection<? extends E> c)
/**
* 将集合中的元素插入到对应位置
*
* @param index
* @param c
* @return
* @throws IndexOutOfBoundsException
* @throws NullPointerException
*/
public boolean addAll(int index, Collection<? extends E> c) {
//检查下标是否越界
rangeCheckForAdd(index);
//集合转数组
Object[] a = c.toArray();
int numNew = a.length;
//检查是否需要扩容
ensureCapacityInternal(size + numNew);
int numMoved = size - index;
if (numMoved > 0)
//将下标之后元素右移一位
System.arraycopy(elementData, index, elementData, index + numNew,numMoved);
//将c中元素插入到指定位置
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
void removeRange(int fromIndex, int toIndex)
/**
* 移除下标位于参数之间的元素
*
* @throws IndexOutOfBoundsException
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
//将元素左移置指定位置
System.arraycopy(elementData, toIndex, elementData, fromIndex,numMoved);
int newSize = size - (toIndex-fromIndex);
//无效元素置空,方便GC回收
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
boolean removeAll(Collection<?> c)
/**
* 将c和当前列表相交的元素全部移除
*/
public boolean removeAll(Collection<?> c) {
//集合c不为空
Objects.requireNonNull(c);
return batchRemove(c, false);
}
/**
* 批量删除元素
* complement 为 true 时,删除c中不包含元素
* complement 为 false 时,删除c中包含元素
*/
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
//读写两个指针遍历
//读指针每次自增1,写指针写入元素才+1
int r = 0, w = 0;
boolean modified = false;
try {
//遍历列表,如果c中有该元素,将该元素放到写指针位置
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
if (r != size) {
System.arraycopy(elementData, r,elementData, w,size - r);
//如果c.contains()抛出异常,则把唯独的元素都拷贝到写指针后面
w += size - r;
}
if (w != size) {
//写指针后面的元素置空,方便GC回收
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
//有修改返回true,否则不然
return modified;
}
```
boolean retainAll(Collection<?> c)
```java
/**
* 与removeAll相反,这是二者的交集
*/
public boolean retainAll(Collection<?> c) {
//c非空
Objects.requireNonNull(c);
//批量删除
return batchRemove(c, true);
}