How Iterator's remove method actually remove an object

不羁的心 提交于 2019-11-27 03:12:21

How exactly Iterator removes elements depends on its implementation, which may be different for different Collections. Definitely it doesn't break the loop you're in. I've just looked how ArrayList iterator is implemented and here's the code:

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

So it checks for concurrent modifications, removes element using public ArrayList remove method, and increments counter of list modifications so ConcurrentModificationException won't be thrown at next iteration.

The reason why you cannot modify a list while iterating over it is because the iterator has to know what to return for hasNext() and next().

How this is done is implementation specific, but you could have a look at the source code of ArrayList/AbstractList/LinkedList etc.

Also note that in some situations you can use some code like this as an alternative:

List<Foo> copyList = new ArrayList<>(origList);
for (Foo foo : copyList){
  if (condition){
    origList.remove(foo);
  }
}

But this code will probably run slightly slower because the collection has to be copied (shallow copy only) and the element to remove has to be searched.

Also note that if you're using the iterator directly it's recommended to use a for loop instead of while loop as this limits the scope of the variable:

for (Iterator<Foo> iterator = myCollection.iterator(); iterator.hasNext();){
...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!