迭代器的remove方法如何实际删除对象

问题描述

Iterator删除元素的确切方式取决于其实现,这对于不同的Collection可能有所不同。绝对不会中断您所处的循环。我只是看了如何实现ArrayList迭代器,下面是代码

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();
    }
}

因此,它检查并发修改,使用公共ArrayList remove 方法删除元素,并递增列表修改的计数器,以便在下一次迭代时不会引发ConcurrentModificationException。

解决方法

我们都知道,在迭代时从集合中删除对象的最安全的“可能也是唯一安全的”方法是,首先检索Iterator,执行循环并在需要时删除;

Iterator iter=Collection.iterator();
while(iter.hasNext()){
    Object o=iter.next()
    if(o.equals(what i'm looking for)){
        iter.remove();
    }
}

我想了解但不幸的是,还没有找到深入的技术解释,即如何执行此删除操作,
如果:

for(Object o:myCollection().getObjects()){
    if(o.equals(what i'm looking for)){
        myCollection.remove(o);
    }
}

会抛出ConcurrentModificationException“技术术语”
Iterator.remove()做什么?它是否会删除对象,中断循环并重新启动循环?

我在官方文档中看到:

“删除当前元素。IllegalStateException如果尝试调用remove()之前未调用next()的方法,则抛出该异常。

“删除当前元素”部分使我想到了在“常规”循环=>中执行的完全相同的情况(执行相等性测试并在需要时删除),但是为什么Iterator循环ConcurrentModification安全?