LinkedList迭代器删除 [英] LinkedList iterator remove
问题描述
可能重复:
在迭代集合时删除元素的高效等价物
private LinkedList flights;
....
public void clear(){
ListIterator itr = flights.listIterator();
while(itr.hasNext()){
flights.remove(itr.next());
}
}
... 。
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
at java.util.LinkedList$ListItr.next(Unknown Source)
at section1.FlightQueue.clear(FlightQueue.java:44)
at section1.FlightTest001.main(FlightTest001.java:22)
它有什么问题?不能理解为什么会给出错误,我确信我在arraylists或数组上使用了相同的代码并且它已经工作了。
Whats wrong with it? cant at all understand why the error is given, I am sure i have used the same code on arraylists or arrays and it has worked.
推荐答案
在迭代元素时,无法直接从集合中删除项目,因为这会导致 ConcurrentModificationException
。 Iterator.remove()
是在迭代期间修改集合的可接受的安全方法。为避免看到 IllegalStateException
,请务必调用 Iterator.next()
:
You cannot remove an item from the collection directly while iterating through the elements as this will cause a ConcurrentModificationException
. Iterator.remove()
is the accepted safe way to modify a collection during iteration. To avoid seeing an IllegalStateException
, make sure to call Iterator.next()
:
while (itr.hasNext()) {
itr.next();
itr.remove();
}
或者你只想删除收藏
,您可以使用:
or as you simply wish to remove all elements in the Collection
, you could use:
flights.clear();
请参阅:在迭代集合时删除元素的高效等价物
See: Efficient equivalent for removing elements while iterating the Collection
这篇关于LinkedList迭代器删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!