我们都知道,在迭代它时从集合中删除对象的最安全的"可能只是安全的"方法是首先检索Iterator,执行循环并在需要时删除;
Iterator iter=Collection.iterator();
while(iter.hasNext()){
Object o=iter.next()
if(o.equals(what i'm looking for)){
iter.remove();
}
}
Run Code Online (Sandbox Code Playgroud)
我想要了解的,并且遗憾的是没有找到深入的技术解释,是如何执行此删除,
如果:
for(Object o:myCollection().getObjects()){
if(o.equals(what i'm looking for)){
myCollection.remove(o);
}
}
Run Code Online (Sandbox Code Playgroud)
抛出一个ConcurrentModificationException,"技术术语" Iterator.remove()做什么?它会删除对象,打破循环并重新启动循环吗?
我在官方文档中看到:
"删除当前元素.
IllegalStateException如果尝试调用remove()之前没有调用next(),则抛出."
部分"删除当前元素",让我想到在"常规"循环中发生的完全相同的情况=>(执行相等性测试并在需要时删除),但为什么Iterator循环ConcurrentModification安全?