();
}
}
当我们使用 ArrayList 容器的 iterator() 方法后,在栈空间里创建了一个此类特定的迭代器对象,同时将成员变量 modCount 的值赋予成员变量 expectedModCount。知道这个有趣的事情后可以先打住,让我们再来看看 ArrayList 类 remove() 方法的源码:
参数为 int 类型的 remove():
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; // clear to let GC do its work
return oldValue;
}
参数为 Object 类型的 remove():
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 remove method that skips bounds checking and does not
* return the value removed.
*/
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
}
以 ArrayList 类里 remove() 方法为例来看,只要我们调用此方法一次,那么 modCount 便自加一次 1。于是我们可以理解,modCount 是一个记录容器对象修改次数的变量,它是一个计数器。小伙伴门完全可以去查源码,不仅仅是 remove(),凡是涉及对 ArrayList 对象的增、删、改的任何一种方法,当我们调用一次这类方法,那 modCount 便会自加一次 1,即,记录一次容器对象的改变。例如,当我创建一个 ArrayList 对象 al 后,我调用 al.add() 一次,调用 al.remove() 一次,再调用 al.add() 一次后,那么 modCount = 3,由此说明 al 被修改了3次。
在没有创建迭代器对象之前的任何对容器对象的增删改操作只会让 modCount 自加,当我们创建一个对应容器类的迭代器对象之后,int expectedModCount = modCount,迭代器对象里的 expectedModCount 成员变量被初始化为与 modCount 里的数值一样的值。
有了迭代器,然后用迭代器进行迭代,就涉及到迭代器对象的 hasNext();next()方法了,我们看下这两个方法的源码:
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];
}
由此可见,两个方法都不会改变 expectedModCount 的值,那怎么理解 expectedModCount 这个成员变量呢?再看迭代器里的 remove() 方法源码:
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
Ar