本文基于JDK8分析总结,如有谬误还请各位大佬指正。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
//初始容量为10
private static final int DEFAULT_CAPACITY = 10;
//存放元素的数组
//顺便一提,transient关键字的作用:在进行序列化的时候,此关键字修饰的成员变量,不会进行序列化操作
transient Object[] elementData;
//数组中存储的元素个数
private int size;
//最大元素个数
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//空数组
private static final Object[] EMPTY_ELEMENTDATA = {};
//这个空数组是为了在第一次放入元素时知道要将它初始化多大
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
}
以下三个构造方法都会对数组进行初始化操作。无参构造方法会将数组初始化为一个长度为0的空数组,在第一次加入元素时会扩容至默认大小10.
public ArrayList() { //无参构造默认初始化一个空数组
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
public ArrayList(int initialCapacity) { //传入的初始容量必须>=0,初始化数组为传入的大小
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else { //初始容量小于0时抛出异常
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
public ArrayList(Collection<? extends E> c) {
//先会将c这个集合对象转为对应类型的数组,toArray方法会调用Arrays.copyOf方法通过反射将c转换为数组
//数组类型为c中单个元素的运行时类,这里单个元素类型可能不是Object
elementData = c.toArray();
if ((size = elementData.length) != 0) { //初始化size成员变量
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class) //转换后的数组不是Object数组,就调用Arrays.copyOf的构造方法,将它转为Object数组
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
ArrayList常用的API无过于增删查改等,所以下面就来看看这些方法。
add(E e)
按顺序向数组中添加元素
步骤
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
//计算数组容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
//无参构造创建时数组为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,这里返回数组默认大小,后面会在grow方法中将它初始化为默认大小,即容量为10的数组
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++; //修改次数变量+1
// overflow-conscious code
if (minCapacity - elementData.length > 0) //如果增加当前元素后数组越界,就需要扩容
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); //可以看到,数组每次扩容至当前的1.5倍大小
//原数组的1.5倍长度还小于需要的数组长度,直接使用需要的数组长度作为新数组长度
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity); //数组容量最大扩容至2^31-1,否则hugeCapacity方法抛出OOM异常
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity); //构建一个newCapacity大小的新数组,并将原数组拷贝到新数组中。
}
Arrays.copyOf()
拷贝数组的工具方法
步骤:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
add(int index, E element)
在指定位置index添加元素
步骤:
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
addAll方法的两个构造方法的步骤和add的两个构造方法差不多,只不过会先将参数中的集合对象通过Arrays.toArray()转为Object数组再进行相应操作。
clear()
将数组中所有元素置空,以便GC回收数组空间
public void clear() {
modCount++; //修改元素次数变量+1
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
remove(int index)
删除数组指定位置的元素
步骤:
public E remove(int index) {
rangeCheck(index); //检查index是否越界
modCount++; //修改元素次数变量+1
E oldValue = elementData(index); //取出index位置的待删除元素
int numMoved = size - index - 1; //numMoved为index到末尾元素的数量(即待移动元素的数量)
if (numMoved > 0)
//将index后的元素向前拷贝size - index - 1个位置
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//将末尾元素置空以便于GC回收末尾元素空间
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
remove(Object o)
移除指定元素
步骤:
分待删除元素是否为null两种情况,但不论待删除元素是否为null,都先进行遍历,找到第一个和待删除元素相等的元素下标index
通过fastRemove方法移除index位置的元素。
fastRemove方法中进行数组拷贝并将末尾元素置空
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++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
//不会越界,不用判断;也不需要取出该元素。
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
removeAll(Collection> c)
移除数组中所有的和集合c共有的元素
步骤:
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w; //修改元素次数变量+(size - w)
size = w;
modified = true;
}
}
return modified;
}
步骤:先进行越界检查,再将元素的引用赋给数组index位置元素
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
步骤:先进行越界检查,再返回指定位置index
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
ArrayList的迭代器实现类,集合类的子类的迭代器的实现都比较类似。
modCount
在上面的增删操作中都会对ArrayList的成员变量modCount加上对数组元素修改的次数(修改几个元素就加几)。它记录了集合当前被修改的次数,在使用ArrayList的迭代器前,它会将modCount赋给自己的成员变量expectedModCount,用于在迭代时判断是否对数组中的元素进行了修改(即增删操作)。
如果迭代时对数组中的元素进行了修改,ArrayList的成员变量modCount就会 > 迭代器的成员变量expectedModCount,下面的checkForComodification方法就会抛出ConcurrentModificationException(并发修改异常)
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//这个方法用来检测数组是否被修改
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}