我们都知道,在迭代时从集合中删除对象的最安全“可能也是唯一安全”的方法是首先检索 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()
是做什么的?它会移除对象、中断循环并重新开始循环吗?
我在官方文档中看到:
"Removes the current element. Throws
IllegalStateException
if an attempt is made to callremove()
that is not preceded by a call to next( )."
“删除当前元素”部分让我想到了“常规”循环中发生的完全相同的情况 =>(执行相等测试并在需要时删除),但为什么迭代器循环 ConcurrentModification 安全?
最佳答案
在迭代列表时不能修改列表的原因是迭代器必须知道 hasNext() 和 next() 返回什么。
具体的实现方式是具体的,但您可以查看 ArrayList/AbstractList/LinkedList 等的源代码。
另请注意,在某些情况下,您可以使用类似这样的代码作为替代:
List<Foo> copyList = new ArrayList<>(origList);
for (Foo foo : copyList){
if (condition){
origList.remove(foo);
}
}
但此代码可能会运行得稍微慢一些,因为必须复制集合(仅限浅复制)并且必须搜索要删除的元素。
另外请注意,如果您直接使用迭代器,建议使用 for 循环而不是 while 循环,因为这会限制变量的范围:
for (Iterator<Foo> iterator = myCollection.iterator(); iterator.hasNext();){
...
}
关于java - Iterator 的 remove 方法实际上是如何删除一个对象的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15993356/