「这是我参与2022首次更文挑战的第19天,活动详情查看:2022首次更文挑战」
源码
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
private static final long serialVersionUID = 8683452581122892189L;
/**
* 默认初始化容量
*/
private static final int DEFAULT_CAPACITY = 10;
/**
* 用于空实例的共享空数组实例
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 用于默认大小的空实例的共享空数组实例
* 我们将它和 EMPTY_ELEMENTDATA 区分开来,以了解当第一个元素被添加时必须要膨胀
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 存储 ArrayList 元素的数组缓存
* ArrayList 容量是这个数组缓存的长度
* 当添加第一个元素时,任何空 elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA 的 ArrayList 将扩展到 DEFAULT_CAPACITY
*/
transient Object[] elementData; // 非私有简化内部类访问
/**
* ArrayList 的大小(它包含元素的数量)
*
* @serial
*/
private int size;
/**
* 构造一个指定初始化容量的空列表
*
*
* @param initialCapacity 列表初始化容量
* @throws IllegalArgumentException 如果指定初始化容量是负的
*/
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;
}
/**
* 构造一个包含指定集合元素的列表,按照集合的迭代器返回的顺序
*
* @param c 元素被代替到这个列表的集合
* @throws NullPointerException 如果指定集合是 null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray 可能(错误地) 不返回 Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// 代替空数组
this.elementData = EMPTY_ELEMENTDATA;
}
}
/**
* 将这个 ArrayList 实例的容量裁剪为列表的当前大小
* 应用程序可以使用这个操作最小化 ArrayList 实例的存储
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
/**
* 增加这个 ArrayList 实例的容量,如果必要的话,确保它至少可以保存最小容量参数指定的元素数量
*
* @param 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;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 溢出意识的代码
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
/**
* 分配数组的最大大小
* 一些虚拟机保留一些头字在数组中
* 尝试分配更大数组可能导致 OutOfMemoryError:请求数组长度超出虚拟机限制
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 增加容量,确保它至少可以保存最小容量参数指定的元素数量
*
* @param minCapacity 期望最小容量
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
/**
* 返回这个列表元素的数量
*
* @return 这个列表元素的数量
*/
public int size() {
return size;
}
/**
* 返回 true,如果这个列表没有包含任何元素
*
* @return <tt>true</tt> 如果这个列表没有包含任何元素
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 返回 true,如果这个列表包含指定元素
* 更正确的说,返回 true,当且仅当这个列表包含至少一个元素 e,满足 (o==null && e==null && o.equals(e))
*
* @param o 要测试是否在这个列表存在的元素
* @return <tt>true</tt> 如果这个列表包含指定元素
*/
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
/**
* 返回指定元素在这个列表第一次出现索引,如果这个列表没有包含这个元素,则为 -1
* 更正确的说,返回最低索引 i,例如 (o==null && get(i)==null && o.equals(get(i))),如果这里没有这样的索引,返回 -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
* 更正确的说,返回最高的索引 i,例如 (o==null ? get(i)==null : o.equals(get(i))),或者 -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 实例的浅拷贝(元素本身不复制)
*
* @return 这个 ArrayList 实例的克隆对象
*/
public Object clone() {
try {
ArrayList<?> v = (ArrayList<?>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// 这不应该发生,因为我们是可克隆的
throw new InternalError(e);
}
}
/**
* 返回按正确顺序(从第一个到最后一个元素)包含这个列表所有元素的数组
*
* 返回的数组是安全的,因为这个集合不维护对它的引用(换句话说,这个方法必须分配一个新数组)
* 因此,调用者可以自由修改返回的数组
*
* 这个方法充当基于数组 API 和基于集合 API 的桥梁
*
* @return 按正确顺序包含这个列表所有元素的数组
*/
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
/**
* 返回按正确的顺序(从第一个元素到最后一个元素)包含这个列表的全部元素的数组;返回数组的运行类型是指定数组的运行类型
* 如果列表符合指定的数组,则返回指定的数组
* 否则,通过指定数组的运行时类型和这个列表的大小分配一个新的数组
*
* 如果这个列表适合指定数组,并且有剩余空间(即,数组中的元素比这个列表中的元素多),数组中紧随集合结束的元素设置为 null
* (只有当调用者知道这个集合没有包含任何 null 元素,才有助于确定这个集合的长度)
*
* @param a 如果数组足够大将此集合的元素存储到其中,否则,因为这个目的分配一个相同运行时类型的新数组
* @return 包含这个列表元素的数组
* @throws ArrayStoreException 如果指定数组的运行时类型不是这个列表中每个元素的运行时类型的父类
* @throws NullPointerException 如果指定数组是 null
*/
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
// 位置访问操作
@SuppressWarnings("unchecked")
E elementData(int index) {
return (E) elementData[index];
}
/**
* 返回这个列表指定位置的元素
*
* @param index 要返回元素的索引
* @return 在这个列表中指定位置的元素
* @throws IndexOutOfBoundsException
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
/**
* 使用指定元素代替这个列表指定位置的元素
*
* @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;
}
/**
* 将指定元素追加到这个列表的末尾
*
* @param e 要追加到这个列表的元素
* @return <tt>true</tt> (按照 Collection#add)
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // 增加 modCount!!
elementData[size++] = e;
return true;
}
/**
* 在这个列表的指定索引插入指定元素
* 将元素移动到当前位置(如果有),并且右边的任何后续元素右移(给它们索引加一)
*
* @param index 要插入指定元素的索引
* @param element 要插入的元素
* @throws IndexOutOfBoundsException
*/
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++;
}
/**
* 移除这个列表指定位置的元素
* 将任何后续的元素向左移 (从它们的索引减一)
*
* @param index 要移除元素的索引
* @return 从这个列表移除的元素
* @throws IndexOutOfBoundsException
*/
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);
elementData[--size] = null; // 允许 GC 完成它的工作
return oldValue;
}
/**
* 从这个列表移除指定元素的第一次出现,如果有
* 如果这个列表不包含指定元素,它不变
* 更准确的说,删除索引最低的元素 i,例如 (o==null && get(i)==null && o.equals(get(i)))(如果这样一个元素存在)
* 如果这个列表包含指定元素,返回 true(或者相当于,如果这个列表因为这个调用结果而改变)
*
* @param o 从这个列表移除的元素,如果存在
* @return <tt>true</tt> 如果这个列表包含指定元素
*/
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;
}
/*
* 私有 remove 方法,跳过边界检查和不会返回被移除的值
*/
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; // 允许GC完成它的工作
}
/**
* 从这个列表移除全部元素
* 这个调用返回后,这个列表将变成空
*/
public void clear() {
modCount++;
// 允许GC完成它的工作
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
/**
* 追加指定集合的所有元素到这个列表的尾部,按照指定集合的迭代器返回的顺序
* 如果指定集合在操作的过程中修改,这个操作的行为不明(这意味着,如果指定集合是这个集合,并且这个集合是非空的,这个调用的行为未定义)
*
* @param c 包含添加到这个列表的元素的集合
* @return <tt>true</tt> 如果这个列表因为这个调用改变
* @throws NullPointerException 如果指定集合是 null
*/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // 增加 modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
/**
* 插入指定集合的所有元素到这个列表,从指定位置开始
* 右移当前位置的元素(如果有)和任何后续元素(增加它们索引)
* 新元素将按指定集合的迭代器返回的顺序出现在列表
*
* @param index 从指定集合插入第一个元素的索引
* @param c 包含要插入到这个列表的元素的集合
* @return <tt>true</tt> 如果这个列表因为调用这个方法改变
* @throws IndexOutOfBoundsException
* @throws NullPointerException 如果指定集合是 null
*/
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // 增加 modCount
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(不包括)的全部元素
* 左移任何后续元素(减少他们的索引)
* 这个调用通过 (toIndex - fromIndex) 元素缩短列表(如果 toIndex==fromIndex,这个操作没有影响)
*
* @throws IndexOutOfBoundsException 如果 fromIndex 或 toIndex 超出范围(fromIndex < 0 || fromIndex >= size() || toIndex > size() || toIndex < fromIndex})
*/
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
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 使用的 rangeCheck 一个版本
*/
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* 构造 IndexOutOfBoundsException 详细信息
* 在错误处理代码在很多可能重构中,这种 “outlining” 在在服务器和客户端虚拟机都表现最好
*/
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+size;
}
/**
* 从这个列表移除指定集合包含的所有元素
*
* @param c 包含从这个列表移除元素的集合
* @return {@code true} 如果这个列表因为调用这个方法改变
* @throws ClassCastException 如果这个列表的元素的类与指定集合不相容
* @throws NullPointerException 如果这个列表包含一个 null 元素,并且指定集合不支持 null 元素,或者指定集合是 null
* @see Collection#contains(Object)
*/
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
/**
* 只保留这个列表包含指定集合的元素
* 换句话说,从这个列表移除全部指定集合不包含的元素
*
* @param c 要保留在这个列表的元素的集合
* @return {@code true} 如果这个列表因为调用这个方法改变
* @throws ClassCastException 如果这个列表的元素的类与指定集合不相容
* @throws NullPointerException 如果这个列表包含一个 null 值,并且指定集合不支持 null 元素,或者指定集合是 null
* @see Collection#contains(Object)
*/
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 {
// 保持和 AbstractCollection 行为兼容性,即使 c.contains() 抛出
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;
modified = true;
}
}
return modified;
}
/**
* 保存 ArrayList 实例的状态到流中(也就是说,序列化它)
*
* @serialData 支持 ArrayList 实例的数组长度(int),按照正确顺序跟随它的全部元素(每一个 Object)
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// 写出元素计数和任何隐藏的东西
int expectedModCount = modCount;
s.defaultWriteObject();
// 写出与 clone() 行为相容的容量大小
s.writeInt(size);
// 按正确顺序写出全部元素
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
/**
* 从流中重组 ArrayList 实例(也就是说,反序列化它)
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// 阅读大小和任何隐藏的东西
s.defaultReadObject();
// 阅读能力
s.readInt(); // 忽略
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();
}
}
}
/**
* 返回这个列表的元素的列表迭代器(按照正确顺序),在这个列表的指定位置开始
* 初始化调用 ListIterator#next 返回指定索引指明的第一个元素
* 初始化调用 ListIterator#previous 返回指定索引为负一的元素
*
* 返回的列表迭代器是快速失败
*
* @throws IndexOutOfBoundsException
*/
public ListIterator<E> listIterator(int index) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: "+index);
return new ListItr(index);
}
/**
* 返回这个列表的元素的列表迭代器(按正确的顺序)
*
* 返回的迭代器是快速失败
*
* @see #listIterator(int)
*/
public ListIterator<E> listIterator() {
return new ListItr(0);
}
/**
* 返回按正确的顺序遍历这个列表的元素的迭代器
*
* 返回的迭代器是快速失败
*
* @return 按正确顺序遍历这个列表的元素的迭代器
*/
public Iterator<E> iterator() {
return new Itr();
}
/**
* AbstractList.Itr的优化版本
*/
private class Itr implements Iterator<E> {
int cursor; // 返回下一个元素的索引
int lastRet = -1; // 返回最后一个元素的索引;如果没有则为 -1
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();
}
}
@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 的优化版本
*/
private class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
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(不包括)区域之间部分的视图(如果 fromIndex 和 toIndex 相等,返回的列表是空)
* 返回的列表是基于这个列表,所以返回列表的非结构改变反应在这个列表,反之亦然
* 返回的列表支持所有可选列表操作
*
* 这个方法不需要明确操作范围(数组通常存在的那种排序)
* 通过操作子列表视图而不是整个列表,任何需要列表操作可以被用作范围操作
* 例如,下面的语法从列表移除一系列元素
* <pre>
* list.subList(from, to).clear();
* </pre>
* 类似的语法也可用于 #indexOf(Object) 和 #lastIndexOf(Object),和 Collections 类的全部算法能够应用于子列表
*
* 如果支持列表(即,这个列表)在结构上改变,而不是通过返回的列表,这个方法返回的列表的语义变成未定义(结构改变会改变列表的大小,或者用某种方式干扰它,正在迭代可能产生错误的结果)
*
* @throws IndexOutOfBoundsException
* @throws IllegalArgumentException
*/
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;
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;
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)];
}
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++)]);
}
// 在迭代结束的时候更新一次,减少堆写入流
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 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();
}
}
/**
* 在这个列表的元素上创建一个延迟半丁和快速失败分离器
*
* 分离器报告 Spliterator#SIZED Spliterator#SUBSIZED 和 Spliterator#ORDERED
* 重写实现应该记录额外特征值的报告
*
* @return 这个列表的元素的分离器
* @since 1.8
*/
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
/** 基于索引的二次拆分,延迟初始化拆分器 */
static final class ArrayListSpliterator<E> implements Spliterator<E> {
/*
* 如果 ArrayList 是不可变的,或者在结构上是不可变的(没有添加、删除等),我们可以用 Arrays.spliterator 实现它们的分离器
* 相反,我们在遍历过程中尽可能多地检测干扰,而不牺牲太多性能
* 我们主要依靠 modCounts.
* 它们不能保证检测到并发冲突,有时对线程内的干扰过于保守,但可以检测到足够多的问题,在实践中是值得的
* 为了实现这一点,我们
* (1) 延迟初始化 fence 和 expectedModCount,直到我们需要提交到我们要检查的状态的最新点;从而提高了精度。(这不适用于使用当前非惰性值创建拆分器的子列表)
* (2) 在 forEach 的末尾,我们只执行一次 ConcurrentModificationException 检查(对性能最敏感的方法)
* 使用 forEach 时(与迭代器相反),我们通常只能在行动之后检测干扰,而不是之前
* 进一步的 CME-triggering 检查适用于全部其他可能违反假设的情况,例如,给定大小的 elementData 数组为 null或太小,这只可能是由于干扰造成的。
* 这使得 forEach 的内部循环可以在不进行任何进一步检查的情况下运行,并简化了 lambda-resolution
* 虽然这确实需要进行一些检查,但请注意,通常情况下 list.stream().forEach(a),除了 forEach 本身之外,任何地方都不会进行检查或其他计算
* 其他不太常用的方法无法利用这些流线型中的大部分
*/
private final ArrayList<E> list;
private int index; // 当前索引,提前/拆分时修改
private int fence; // -1 直到使用;然后最后一个索引
private int expectedModCount; // 设置围栏时初始化
/** 创建一个分离器覆盖给定的范围 */
ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
int expectedModCount) {
this.list = list; // 如果为 null,则 OK,除非遍历
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
private int getFence() { // 第一次使用时初始化栅栏大小
int hi; // (一个特殊变形出现在方法 forEach)
ArrayList<E> lst;
if ((hi = fence) < 0) {
if ((lst = list) == null)
hi = fence = 0;
else {
expectedModCount = lst.modCount;
hi = fence = lst.size;
}
}
return hi;
}
public ArrayListSpliterator<E> trySplit() {
int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
return (lo >= mid) ? null : // 将范围一分为二,除非太小
new ArrayListSpliterator<E>(list, lo, index = mid,
expectedModCount);
}
public boolean tryAdvance(Consumer<? super E> action) {
if (action == null)
throw new NullPointerException();
int hi = getFence(), i = index;
if (i < hi) {
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; // 提升从循环进入和检查
ArrayList<E> lst; Object[] a;
if (action == null)
throw new NullPointerException();
if ((lst = list) != null && (a = lst.elementData) != null) {
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() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
@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; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
@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++;
}
@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++;
}
}