一 简介
该类实现了一个大小可变的有序集合,对其的操作拥有数组的特性。
支持存储所有类型的数据,包括null值。
除了没有实现同步操作,其他基本等同于Vector
与LinkList类相比,常量因子较低
二 成员变量
首先看到了ArrayList继承了AbstractList,提供了List接口的骨干实现,减少了实现ArrayList所需的工作。
实现了List接口,提供了List集合的基本方法。
实现了RandomAccessFile,这是一个空的接口,仅仅起到标识作用,代表实现这个接口的类拥有随机存储的功能。
实现了Cloneable,这是一个空的接口,仅仅起到标识作用,代表实现这个接口的类支持.clone
方法。如果在没有实现这个接口的类上调用.clone
方法,则会抛出CloneNotSupportedException
异常。
实现了RandomAccessFile,这是一个空的接口,仅仅起到标识作用,代表实现这个接口的类拥有序列化及反序列化的功能。
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
}
首先看一下成员变量:
// 初始化的默认集合容量
private static final int DEFAULT_CAPACITY = 10;
// 用于空实例的共享空数组实例。当ArrayList初始化传入参数为0时使用该成员变量
private static final Object[] EMPTY_ELEMENTDATA = {};
// 用于空实例的共享空数组实例,当ArrayList初始化不传入参数时使用该成员变量,跟EMPTY_ELEMENTDATA的区别是其默认大小为DEFAULT_CAPACITY,即10。
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
// 利用该数组缓存存储在ArrayList的元素,容量即是该数组缓存的长度。如果一个空数组是引用自DEFAULTCAPACITY_EMPTY_ELEMENTDATA的话,当数组缓存添加了第一个元素时,该数组缓存长度将会被拓展至DEFAULT_CAPACITY默认长度、
transient Object[] elementData; // 设置为非私有以简化内部类的访问 ???
// 数组缓存包含元素的大小
private int size;
三 构造函数
// 利用指定的集合长度构建一个空的数组缓存,若指定长度小于0则抛出非法数据异常
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;
}
// 构造一个包含指定集合元素的list,并通过集合的迭代器按序将元素返回
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray可能不会返回一个Object[]类型
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
this.elementData = EMPTY_ELEMENTDATA;
}
}
看一下构造函数中调用到的其他方法,也是在ArrayList类中实现:
// 返回一个数组,该数组按正确的顺序(从第一个元素到最后一个元素)包含列表中的所有元素。
// 这个方法将为其分配一个新的数组,因此不会影响到之前的集合,从外部调用的话可以当成一个把集合数据转化为数组数据的方法。
public Object[] toArray() {
// 复制指定长度的类型元素,并且返回的元素拥有与elementData相同的运行时类型。
return Arrays.copyOf(elementData, size);
}
// 返回一个数组,该数组按适当的顺序(从第一个元素到最后一个元素)包含列表中的所有元素;
// 返回数组的运行时类型是指定数组的运行时类型。如果列表符合指定的数组,则在其中返回该列表。否则,将使用指定数组的运行时类型和此列表的大小分配新数组。
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// 复制指定长度的类型元素,并且返回的元素拥有与a相同的运行时类型
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
// 是一个native方法,将elementData从0开始的元素复制到数组a从0到size - 1范围的位置
System.arraycopy(elementData, 0, a, 0, size);
// 设置a[size]为数组缓存复制的结尾
if (a.length > size)
a[size] = null;
return a;
}
四 容量操作
// 将本实例的容量调整至size的大小
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
// 确保集合的容量增长的值能够满足最小容量需求minCapacity,并确保它能够容纳最小容量参数minCapacity的元素。可供用户调用。
public void ensureCapacity(int minCapacity) {
// 最小拓容
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// 如果不是默认元素则为任意大小
? 0
// 对于默认空表,则设置为默认值
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
// 计算容量,为扩容作准备。
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
// 用来检查是否需要扩容,比如在add、addAll方法,需要事先检查一下数组列表是否满了。
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 只要最小需求容量大于集合当前容量,则增大容量
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
// 确保集合的容量增长的值能够满足最小容量需求minCapacity,并确保它能够容纳最小容量参数minCapacity的元素。
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1); // >>相当于除以2,一般情况下,每一次扩容,会将容量扩展至原来的 1.5 倍。
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
// 将新的容量设置为 hugeCapacity 方法返回的值
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
// 若minCapacity > MAX_ARRAY_SIZE,则直接将minCapacity设置为Integer.MAX_VALUE,避免下一次因为小的容量增长而进行再次拓容。
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0)
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
五 常用API
// 返回列表中元素的数量。
public int size() {
return size;
}
// 如果此列表为空,则返回true
public boolean isEmpty() {
return size == 0;
}
// 如果此列表包含指定元素,则返回true
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
// 返回指定元素在该列表中第一次出现位置的索引,若列表中不存在该元素则返回-1
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
// 返回指定元素在该列表中最后一次出现位置的索引,若列表中不存在该元素则返回-1
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
// 返回这个ArrayList实例的浅拷贝
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
// 位置访问操作
// 返回列表中指定位置的元素。
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
// 返回列表中指定位置的元素。
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
// 将列表中指定位置的元素替换为指定的元素,并返回原来指定位置上的值。
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
// 将指定的元素追加到此列表的末尾,永远返回true
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
// 将指定元素插入此列表的指定位置
public void add(int index, E element) {
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1);
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
// 删除列表中指定位置的元素,并返回被删除的元素
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
// 清除,让GC执行它的工作
elementData[--size] = null;
return oldValue;
}
// 从该列表中删除指定元素的第一个出现项并返回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++)
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);
// 清除,让GC执行它的工作
elementData[--size] = null;
}
// 从该列表中删除所有元素。此调用返回后,列表将为空。
public void clear() {
modCount++;
// 清除,让GC执行它的工作
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
// 将指定集合中的所有元素按指定集合的迭代器返回的顺序追加到此列表的末尾。如果在操作进行时修改了指定的集合,则此操作的行为未定义。(这意味着如果指定的集合是这个列表,并且这个列表是非空的,那么这个调用的行为是未定义的。)
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew);
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
// 从指定的位置开始,将指定集合中的所有元素插入此列表。新元素将按指定集合的迭代器返回的顺序出现在列表中。插入成功返回true
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);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
// 移除掉在fromIndex与toIndex之间的所有元素,范围为[fromIndex,toIndex)
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
//检查给定的索引是否在范围内。如果没有,抛出一个合适的运行时异常。此方法不检查索引是否为负:它总是在数组访问之前被调用,如果索引为负,则抛出ArrayIndexOutOfBoundsException。
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// 用于add与addAll的索引范围检查版本
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// 构造一个过界异常细节信息
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
// 从该列表中删除指定集合中包含的所有元素。
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
// 移除掉词列表中所有没有包含在指定集合的元素
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
// 批量移除元素
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 {
// 即使c.contains()抛出,也要保持与AbstractCollection的行为兼容性。
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// 清除,让GC执行它的工作
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
// 将实例的状态存储到一个流里
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// 写出元素计数和所有隐藏的东西
int expectedModCount = modCount;
s.defaultWriteObject();
// 写出大小作为与克隆行为相容性的容量()
s.writeInt(size);
// 按适当的顺序写出所有的元素。
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
// 防止在存储期间对该实例进行了操作
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
// 从流中重新构造实例
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// 读取大小,以及任何隐藏的东西
s.defaultReadObject();
// 读取容量
s.readInt(); // ignored
if (size > 0) {
// 类似于clone(),根据大小而不是容量分配数组
int capacity = calculateCapacity(elementData, size);
SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, capacity);
ensureCapacityInternal(size);
Object[] a = elementData;
// 按正确的顺序读取所有元素。
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
六 迭代器
// 从列表中指定的位置开始,对该列表中的元素(以适当的顺序)返回一个列表迭代器。
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
// 返回列表中元素的列表迭代器(按正确的顺序)。
public ListIterator<E> listIterator() {
return new ListItr(0);
}
// 以适当的顺序返回列表中元素的迭代器。
public Iterator<E> iterator() {
return new Itr();
}
// 这是一个优化过的迭代器版本,是一个内部私有类
private class Itr implements Iterator<E> {
int cursor; // 要返回的下一个元素的索引
int lastRet = -1; // 返回的上一个元素的索引;如果没有就为-1
int expectedModCount = modCount;
Itr() {}
// 判断下个元素是否存在,存在则返回true
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];
}
// 移除掉上一个迭代返回的元素,由于移除一次之后lastRet就被设置为-1,因此不能连续调用两次
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();
}
}
// 遍历消费掉剩下的元素,Consumer是一个消费型函数式接口,代表了接受一个输入参数并且无返回的操作
@Override
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = ArrayList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[i++]);
}
// 在迭代结束时更新一次,以减少堆写流量
cursor = i;
lastRet = i - 1;
checkForComodification();
}
// 防止多线程并发修改
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
// 一个优化的AbstractList.ListItr版本,私有内部类,继承了Itr类的实现,减少了实现ListItr所需的工作。
private class ListItr extends Itr implements ListIterator<E> {
// 构造函数,调用Iir的构造函数并将初始元素索引替换为index
ListItr(int index) {
super();
cursor = index;
}
// 如果当前迭代器指向元素之前存在元素,则返回true
public boolean hasPrevious() {
return cursor != 0;
}
// 返回当前迭代器指向元素的索引
public int nextIndex() {
return cursor;
}
// 返回当前迭代器指向元素的上一个索引
public int previousIndex() {
return cursor - 1;
}
// 将当前迭代器指向上一次元素并返回该元素的值
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[lastRet = i];
}
// 为本迭代器指向的上一个元素设置新值
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 在迭代器指向的元素位置插入一个新值
public void add(E e) {
checkForComodification();
try {
int i = cursor;
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
七 范围操作
此处许多操作都与上面的基本操作类似,但需要考虑加入偏移量、范围起点、范围终点的因素。另外还要考虑并发导致的数据修改。
// 返回指定的[fromIndex, toIndex)区间内的列表,可以利用该方法对列表进行范围操作,例如使用list.subList(from, to).clear();可以清除该范围内的列表数据
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
// 判断取的列表范围是否合法
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}
// 对列表进行范围操作的类,是一个私有内部类
private class SubList extends AbstractList<E> implements RandomAccess {
private final AbstractList<E> parent; // 设置为列表的引用
private final int parentOffset; // 选定范围的起点
private final int offset; // 偏移量
int size; // 范围的大小
// 截取parent
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}
// 将选定范围内的指定索引上的值设置为指定值并返回原本的值
public E set(int index, E e) {
rangeCheck(index);
checkForComodification();
E oldValue = ArrayList.this.elementData(offset + index);
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
// 返回选定范围内的指定索引上的值
public E get(int index) {
rangeCheck(index);
checkForComodification();
return ArrayList.this.elementData(offset + index);
}
// 返回选定范围的长度
public int size() {
checkForComodification();
return this.size;
}
// 在选定范围内的指定索引上的尾部设置指定值
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
// 将选定范围内的指定索引上的值移除并返回该值
public E remove(int index) {
rangeCheck(index);
checkForComodification();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
// 将选定范围内的值移除
protected void removeRange(int fromIndex, int toIndex) {
checkForComodification();
parent.removeRange(parentOffset + fromIndex,
parentOffset + toIndex);
this.modCount = parent.modCount;
this.size -= toIndex - fromIndex;
}
// 将指定集合的值添加进选定范围内的尾部
public boolean addAll(Collection<? extends E> c) {
return addAll(this.size, c);
}
// 将指定集合的值添加进选定范围内的指定索引后面
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
int cSize = c.size();
if (cSize==0)
return false;
checkForComodification();
parent.addAll(parentOffset + index, c);
this.modCount = parent.modCount;
this.size += cSize;
return true;
}
// 构建迭代器
public Iterator<E> iterator() {
return listIterator();
}
// 构建迭代器..
public ListIterator<E> listIterator(final int index) {
checkForComodification();
rangeCheckForAdd(index);
final int offset = this.offset;
return new ListIterator<E>() {
int cursor = index;
int lastRet = -1;
int expectedModCount = ArrayList.this.modCount;
// 若存在下一个元素则返回true
public boolean hasNext() {
return cursor != SubList.this.size;
}
// 返回指定范围迭代器的当前指向元素
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= SubList.this.size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[offset + (lastRet = i)];
}
// 判断指定范围迭代器当前指向元素之前是否存在元素,存在则返回true
public boolean hasPrevious() {
return cursor != 0;
}
// 返回指定范围迭代器当前指向元素之前的元素
@SuppressWarnings("unchecked")
public E previous() {
checkForComodification();
int i = cursor - 1;
if (i < 0)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i;
return (E) elementData[offset + (lastRet = i)];
}
// 遍历并消费指定范围内的元素
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
Objects.requireNonNull(consumer);
final int size = SubList.this.size;
int i = cursor;
if (i >= size) {
return;
}
final Object[] elementData = ArrayList.this.elementData;
if (offset + i >= elementData.length) {
throw new ConcurrentModificationException();
}
while (i != size && modCount == expectedModCount) {
consumer.accept((E) elementData[offset + (i++)]);
}
// update once at end of iteration to reduce heap write traffic
lastRet = cursor = i;
checkForComodification();
}
// 将指定范围的迭代器指向下一个元素索引
public int nextIndex() {
return cursor;
}
// 返回当前指定范围的迭代器指向索引的上一个元素索引
public int previousIndex() {
return cursor - 1;
}
// 移除掉当前指定范围的迭代器当前指向的元素
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
SubList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 将指定值赋值给指定范围的迭代器当前指向元素的上一个元素
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 在当前范围的迭代器指向元素处添加指定值,并将该元素及其后面的元素往右移
public void add(E e) {
checkForComodification();
try {
int i = cursor;
SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
// 检查数组缓存是否被修改过
final void checkForComodification() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
};
}
// 继续划出一个范围内的集合
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
}
// 检查索引会不会过界
private void rangeCheck(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// 检查索引会不会过界,在添加元素时使用该方法进行检查
private void rangeCheckForAdd(int index) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
// 构造过界信息
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+this.size;
}
// 检查数组缓存是否被修改过
private void checkForComodification() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
}
// 构造一个可分割迭代器
public Spliterator<E> spliterator() {
checkForComodification();
return new ArrayListSpliterator<E>(ArrayList.this, offset,
offset + this.size, this.modCount);
}
}
八 可分割迭代器
// 构造一个可分割迭代器
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
// 基于索引的2乘2的延迟初始化Spliterator
static final class ArrayListSpliterator<E> implements Spliterator<E> {
private final ArrayList<E> list; // 用于存放ArrayList对象
private int index; // 起始位置(包含),advance/split操作时会修改
private int fence; // 结束位置(不包含),-1 表示到最后一个元素
private int expectedModCount; // 用于存放list的modCount
// 创建覆盖给定范围的新spliterator
ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
int expectedModCount) {
this.list = list;
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
// 获取结束位置(存在意义:首次初始化时需对fence和expectedModCount进行赋值)
private int getFence() { // 在第一次使用时初始化fence的大小为size
int hi; // 在方法forEach中出现一个专门的变体
ArrayList<E> lst;
// fence<0时(第一次初始化时,fence才会小于0):
if ((hi = fence) < 0) {
// list 为 null时,fence=0
if ((lst = list) == null)
hi = fence = 0;
else {
//否则,fence = list的长度。
expectedModCount = lst.modCount;
hi = fence = lst.size;
}
}
return hi;
}
// 分割list,返回一个新分割出的spliterator实例
public ArrayListSpliterator<E> trySplit() {
//hi为当前的结束位置
//lo 为起始位置
//min为中间的位置
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
//当lo>=mid,表示不能在分割,返回null
//当lo<mid时,可分割,切割(lo,mid)出去,同时更新index=mid
return (lo >= mid) ? null : // 把范围分成两半,除非太小
new ArrayListSpliterator<E>(list, lo, index = mid,
expectedModCount);
}
// 若还有元素仍未处理,返回true并将起始位置向前一位
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null)
throw new NullPointerException();
//hi为当前的结束位置
//i 为起始位置
int hi = getFence(), i = index;
if (i < hi) {
// 处理i位置,index+1
index = i + 1;
@SuppressWarnings("unchecked") E e = (E)list.elementData[i];
action.accept(e);
//遍历时,结构发生变更,抛错
if (list.modCount != expectedModCount)
throw new ConcurrentModificationException();
return true;
}
return false;
}
// 顺序遍历处理所有剩下的元素
public void forEachRemaining(Consumer<? super E> action) {
int i, hi, mc; // hoist accesses and checks from loop
ArrayList<E> lst; Object[] a;
if (action == null)
throw new NullPointerException();
if ((lst = list) != null && (a = lst.elementData) != null) {
// 当fence<0时,表示fence和expectedModCount未初始化
if ((hi = fence) < 0) {
mc = lst.modCount;
hi = lst.size;
}
else
mc = expectedModCount;
if ((i = index) >= 0 && (index = hi) <= a.length) {
for (; i < hi; ++i) {
@SuppressWarnings("unchecked") E e = (E) a[i];
action.accept(e);
}
if (lst.modCount == mc)
return;
}
}
throw new ConcurrentModificationException();
}
// 返回剩下元素的大小
public long estimateSize() {
return (long) (getFence() - index);
}
public int characteristics() {
// 打上特征值:、可以返回size
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
七 其他
// 遍历并消费所有元素
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
// 移除所有满足filter的元素
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
// 找出要删除的元素, 在此阶段从筛选器抛出的任何异常都不会修改集合
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// 将剩余的元素移动到被删除的元素留下的空间上
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
for (int k=newSize; k < size; k++) {
elementData[k] = null;
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
// 替代所有满足UnaryOperator的元素
@Override
@SuppressWarnings("unchecked")
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
// 按传入的Comparator进行排序
@Override
@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
九 问题
为什么ArrayList的最大容量定义如下:
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
因为在JVM虚拟机中需要在数组中存储一些头信息,因此需要出让一些存储空间。