容器 ArrayList源码解析
标签(空格分隔): 容器 ArrayList
ArrayList继承自AbstractList
//实现了三个接口,可克隆,可随机访问(这个有意思,先放放),可序列化
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
//序列化ID
private static final long serialVersionUID = 8683452581122892189L;
//默认容器大小
private static final int DEFAULT_CAPACITY = 10;
//默认空数据???
private static final Object[] EMPTY_ELEMENTDATA = {};
//???
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
//???
transient Object[] elementData;
//容器大小
private int size;
//指定大小初始化
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;
}
//指定容器,初始化
public ArrayList(Collection<? extends E> c) {
//将容器中的值赋值给当前的数组
elementData = c.toArray();
//判断数组的大小,不为0
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
//如果数组类型不是Object类型则返回一个Object类型的数组,并赋值给当前数组
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
//赋值一个空数组
this.elementData = EMPTY_ELEMENTDATA;
}
}
//
public void trimToSize() {
//记录操作次数,防止多线程异常
modCount++;
//将当前数组大小进行比较,如果尺寸小于数组大小,则进行重新赋值
if (size < elementData.length) {
//如果size是0,则直接赋值一个空数组,否则就根据实际大小创建一个新数组赋值返回
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
//扩容
public void ensureCapacity(int minCapacity) {
//计算当前大小
//判断当前容器数组是否为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,如果等于则说明当前的容器数组已经做扩容重新赋值操作了
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
//比较,然后扩容
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
//扩容
private void ensureCapacityInternal(int minCapacity) {
//在默认值和设置值中取最大值
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
//扩容
ensureExplicitCapacity(minCapacity);
}
//扩容
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// 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;
//新数组的大小扩容1.5倍
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;
}
//当前容器尺寸
public int size() {
return size;
}
//判断当前容器是否为空
public boolean isEmpty() {
return size == 0;
}
//判断当前容器是否包含指定元素
public boolean contains(Object o) {
//内部计算:直接使用indexOf,在数组中查找当前元素在数组中的索引,只有大于或等于0才表示存在
return indexOf(o) >= 0;
}
//获取当前元素在容器数组中的索引位置
public int indexOf(Object o) {
//for循环,便利寻找
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;
}
//获取当前元素在容器数组中的最后一个的索引位置,到倒着查找
public int lastIndexOf(Object o) {
//for循环,遍历寻找
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;
}
//clone
public Object clone() {
try {
//调用父类的方法,Object的internalClone方法,克隆一个ArrayList对象
ArrayList<?> v = (ArrayList<?>) super.clone();
//赋值一个当前数组的所有元素,并制定大小赋值给可能的ArrayList的容器数组
v.elementData = Arrays.copyOf(elementData, size);
//操作数设置为0
v.modCount = 0;
//返回这个ArrayList
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError(e);
}
}
//将这个容器数组复制一份然后返回,内部创建了一个新数组
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
//这个和AbstractList中的方法差不多,如果传入数组的尺寸小于当前容器数组,则直接将我们自己的数组转化为传入数组的类型,然后赋值给a返回,占据a从0开始的索引位置
//这个方法有个特点,就是如果我们传入的数组的大小如果小于当前容器的大小,则我们当它只是传进来了一个类型,我们返回的就是还是之前同样大小的数组,不过类型变成了chuant大于当前容器的大小,则设置一个“隔断”,然后将传入的数组返回,如果恰好相等,则不作操作,直接返回传入的数组;
//后面这样做的意思,确实有点没看懂是啥意思???
@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);
//如果传入数组的大小大于当前容器尺寸,则将最后一个“隔断”处设置值为null,最返回传入的数组
if (a.length > size)
a[size] = null;
return a;
}
//根据索引获取当前容器数组中该索引对应的元素
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}
//制定某个索引位置,将值设置为我们传入的值
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
//添加一个指定元素到容器数组中来
public boolean add(E e) {
//先做扩容判断
ensureCapacityInternal(size + 1); // Increments modCount!!
//数组索引位置做+1操作,然后赋值
elementData[size++] = e;
return true;
}
//添加指定元素到指定索引
public void add(int index, E element) {
//对索引做边界值检查
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//扩容操作
ensureCapacityInternal(size + 1); // Increments modCount!!
//索引位置开始,所有位置的元素做后移一位操作
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
//索引位置赋值
elementData[index] = element;
//容器数组大小做+1操作
size++;
}
//指定索引位置做移除操作
public E remove(int index) {
//边界值检查
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
//操作数+1
modCount++;
//获取当前容器数组指定索引位置的元素
E oldValue = (E) elementData[index];
//计算出需要前移的元素数量
int numMoved = size - index - 1;
//如果需要前移操作(如果索引对应最后一位则不需要操作),做前移操作
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//将前移后的容器数组的最后一位位置设置为null
elementData[--size] = null; // clear to let GC do its work
//返回之前该索引位置的元素
return oldValue;
}
//从容器数组中移除指定元素,只能删除第一个
public boolean remove(Object o) {
//for循环,便利寻找,然后做fastRemove操作
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) {
//操作数+1
modCount++;
//计算出需要做前移操作的元素个数
int numMoved = size - index - 1;
//如果需要做前移操作,则做前移操作
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
//容器数组的最后一个元素赋值null
elementData[--size] = null; // clear to let GC do its work
}
//做清理操作
public void clear() {
//操作数+1
modCount++;
//for循环,遍历将元素所在位置赋值为null
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
//大小设置为0
size = 0;
}
//将指定容器中的元素添加到当前容器中
public boolean addAll(Collection<? extends E> c) {
//获取当前容器中的数组
Object[] a = c.toArray();
//获取数组大小
int numNew = a.length;
//做扩容操作
ensureCapacityInternal(size + numNew); // Increments modCount
//将指定容器数组中的元素从当前容器数组的后面累记赋值
System.arraycopy(a, 0, elementData, size, numNew);
//容器大小增加
size += numNew;
//只要传入进来的容器不为空则为true
return numNew != 0;
}
//同上,不同处为不再是直接在当前容器的元素后面累计赋值,而是指定索引位置进行插入赋值
public boolean addAll(int index, Collection<? extends E> c) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments 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;
}
//移除指定索引范围内的元素
protected void removeRange(int fromIndex, int toIndex) {
// Android-changed: Throw an IOOBE if toIndex < fromIndex as documented.
// All the other cases (negative indices, or indices greater than the size
// will be thrown by System#arrayCopy.
//边界值检查
if (toIndex < fromIndex) {
throw new IndexOutOfBoundsException("toIndex < fromIndex");
}
//操作数+1
modCount++;
//计算出需要前移的元素个数
int numMoved = size - toIndex;
//将该数组指定结束位置的数组索引开始往前移动到指定开始位置索引处
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
//计算出移除数组后数组的大小
int newSize = size - (toIndex-fromIndex);
//将后面的元素做赋值null操作
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
//size
size = newSize;
}
//
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++)
//removeAll和retainAll的作用正好相反,一个是保留两个容器中的原容器中的不同元素,一个是保留两个容器中的原容器中相同元素;这块很厉害,开始看的时候差点看迷糊了;
//在complement为true的情况下,如果有两个容器中相同的元素,则加入到当前容器中,从0开始累记赋值,rerainAll的作用
//在complement为true的情况下,如果当前指定容器不是容器中的元素,则将不是容器中的元素加入到数组中,达到移除指定元素的目的,也就是removeAll的作用
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
//按照正确的流程走,r是会等于size的
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
//complement为true的时候,就是从赋值之后的位置都为null,也就是取交集操作
//complement为false的时候,w=0;也就是全部做赋值null操作
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;
}
//将当前容器数组通过对象输出流输出内存
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
//for循环遍历写入到流中
// Write out all elements in the proper order.
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;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
//扩容
ensureCapacityInternal(size);
//遍历读取到数组中
Object[] a = elementData;
// Read in all elements in the proper order.
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);
}
//迭代器,默认游标位置为0
public ListIterator<E> listIterator() {
return new ListItr(0);
}
//迭代器
public Iterator<E> iterator() {
return new Itr();
}
//迭代器
private class Itr implements Iterator<E> {
//容器大小
protected int limit = ArrayList.this.size;
//游标
int cursor; // index of next element to return
//游标上一个的标记
int lastRet = -1; // index of last element returned; -1 if no such
//操作数
int expectedModCount = modCount;
//判断是否还有下一个
public boolean hasNext() {
//判断游标是否小于size,游标和size都是从1开始计数的,所以一旦等于就没有下一个了
return cursor < limit;
}
//获取迭代器下一个元素
@SuppressWarnings("unchecked")
public E next() {
//做操作数检查
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
//获取当前游标
int i = cursor;
//边界值检查
if (i >= limit)
throw new NoSuchElementException();
//获取当前容器数组
Object[] elementData = ArrayList.this.elementData;
//边界值检查
if (i >= elementData.length)
throw new ConcurrentModificationException();
//游标往下走一位
cursor = i + 1;
//返回游标的上一个位置元素,也就是lastRet和i,记录的上一个游标的位置的索引
return (E) elementData[lastRet = i];
}
//移除迭代器当前元素
public void remove() {
//边界值检查
if (lastRet < 0)
throw new IllegalStateException();
//操作数检查
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
//指定索引位置移除,游标往回走一位,容器大小减少一个
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
limit--;
} 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++]);
}
// update once at end of iteration to reduce heap write traffic
//重新获取并设置游标位置
cursor = i;
lastRet = i - 1;
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
}
//迭代器
private class ListItr extends Itr implements ListIterator<E> {
//指定当前游标位置
ListItr(int index) {
super();
cursor = index;
}
//判断是否有上一个
public boolean hasPrevious() {
return cursor != 0;
}
//判断当前下一个元素的索引,cursor是从1开始计数,索引是从0开始计数,所以这个返回cursor刚好返回下一个元素的索引
public int nextIndex() {
return cursor;
}
//获取上一个元素的索引,也就是当前元素的索引
public int previousIndex() {
return cursor - 1;
}
//获取上一个元素
@SuppressWarnings("unchecked")
public E previous() {
//边界值检查
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
//获取上一个元素的索引
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];
}
//设置值,普通的cursor往前走主要是执行了next方法,例如获取了索引为0的数组元素,此时cursor的值为1
public void set(E e) {
if (lastRet < 0)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
//当前游标的上一个元素位置设置对应的值,cursor基本上始终保持在前一个索引位置
try {
ArrayList.this.set(lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
//添加指定元素,在当前迭代器遍历到的位置后面追加
public void add(E e) {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
try {
//获取当前游标
int i = cursor;
//插入值
ArrayList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = modCount;
limit++;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
}
//截取容器用来显示,这里只是显示截取,本质上并没有变动
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 + ")");
}
//截取List,基本操作和AbstractList差不多,不过这个是基于AbstractList来操作的,而且多加入了parent和parentOffset;
//其余的基本都是代理模式,主要是操作传进来的AbstractList的显示
//https://blog.youkuaiyun.com/xiey94/article/details/98087719
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) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
E oldValue = (E) ArrayList.this.elementData[offset + index];
ArrayList.this.elementData[offset + index] = e;
return oldValue;
}
public E get(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
return (E) ArrayList.this.elementData[offset + index];
}
public int size() {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
return this.size;
}
public void add(int index, E e) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
//调用父类AbstractList的add方法,然后子类ArrayList继承自AbstractList,重写add方法,最终调用ArrayList的add方法
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}
public E remove(int index) {
if (index < 0 || index >= this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
E result = parent.remove(parentOffset + index);
this.modCount = parent.modCount;
this.size--;
return result;
}
protected void removeRange(int fromIndex, int toIndex) {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
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) {
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
int cSize = c.size();
if (cSize==0)
return false;
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
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) {
if (ArrayList.this.modCount != this.modCount)
throw new ConcurrentModificationException();
if (index < 0 || index > this.size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(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() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
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() {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
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;
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
}
public int nextIndex() {
return cursor;
}
public int previousIndex() {
return cursor - 1;
}
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
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();
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
try {
ArrayList.this.set(offset + lastRet, e);
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
public void add(E e) {
if (expectedModCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
try {
int i = cursor;
SubList.this.add(i, e);
cursor = i + 1;
lastRet = -1;
expectedModCount = ArrayList.this.modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
};
}
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, offset, fromIndex, toIndex);
}
private String outOfBoundsMsg(int index) {
return "Index: "+index+", Size: "+this.size;
}
public Spliterator<E> spliterator() {
if (modCount != ArrayList.this.modCount)
throw new ConcurrentModificationException();
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]);
}
// Android-note:
// Iterator will not throw a CME if we add something while iterating over the *last* element
// forEach will throw a CME in this case.
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
@Override
public Spliterator<E> spliterator() {
return new ArrayListSpliterator<>(this, 0, -1, 0);
}
static final class ArrayListSpliterator<E> implements Spliterator<E> {
private final ArrayList<E> list;
private int index; // current index, modified on advance/split
private int fence; // -1 until used; then one past last index
private int expectedModCount; // initialized when fence set
/** Create new spliterator covering the given range */
ArrayListSpliterator(ArrayList<E> list, int origin, int fence,
int expectedModCount) {
this.list = list; // OK if null unless traversed
this.index = origin;
this.fence = fence;
this.expectedModCount = expectedModCount;
}
private int getFence() { // initialize fence to size on first use
int hi; // (a specialized variant appears in method 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 : // divide range in half unless too small
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; // 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) {
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);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
int removeCount = 0;
//BitSet有意思,之后研究一下 ???
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();
}
// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
//nextClearBit返回第一个位出现或之后指定的起始索引被设置为false的索引。这样直接看可能不太好理解,我查资料和尝试使用之后可以这么解释:
//这就相当于一个用于记录位置的列表,他的默认值都是false,只有我们设置(set)过的索引位置才不为false;
//例如我们使用[bitSet.set(0),bitSet.set(2),bitSet.set(5)],这就表明,在这个列表中,索引为0,2,5的这三个位置都不为false,而我们调用bitset.set(0),在返回当前以及之后第一个为false的元素的索引,对应到我们的demo,就是1;
//下面的代码就是,我们获取我们要移除的元素的索引,这些都已经标记了不为false,其余的都为false;
//避开这些标记了的,然后将其余的的添加到数组元素中
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();
}
//操作数+1操作
modCount++;
}
return anyToRemove;
}
//这个有点像AOP横切操作符,可以在每个元素使用前做一个预处理
@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++) {
//预处理,然后回调到之前的数组位置,有点像RxJava/java操作符的意思
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++;
}
}