Alei最近和迭代器较上了劲,之前自以为深究过迭代器,不成想原来是坐井观天,以蠡测海。上文中写的东西哪里算什么深入探究?!但亡羊补牢,犹未迟也,经我多次试验,终于弄懂其中某些精巧机制,闲话少说,我们进入正题。
注意,之后所有的知识点都以 ArrayList 这个容器类为例来进行详细说明
在讨论这个问题之前我们得首先在意两个成员变量:
1、ArrayList 类里继承于 AbstractList 类的成员变量 modCount:
protected transient int modCount = 0;
2、ArrayList 类的私有内部类 Itr 里的成员变量 expectedModCount:
int expectedModCount = modCount;
再看下Itr类源码:
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;
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++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }
final void checkForComodification() {
        if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    }
}
当我们使用 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;
}

