陷入“java.util.ConcurrentModificationException”
这是我的代码:
// eventList is a LinkedList
public void run() {
Iterator<Event> it = eventList.iterator();
int size = eventList.size();
while(size > 0) {
while(it.hasNext()) {
Event e = it.next(); //flaged line
if(e.ready()) {
System.out.println(e);
e.action();
eventList.remove(e);
--size;
}
}
}
}
错误java.util.ConcurrentModificationException
在标记内衬(Event e = it.next();
)处抛出。您是否发现我的代码中存在一个错误,该错误清楚地表明了引发该异常的原因?
Here is my code:
// eventList is a LinkedList
public void run() {
Iterator<Event> it = eventList.iterator();
int size = eventList.size();
while(size > 0) {
while(it.hasNext()) {
Event e = it.next(); //flaged line
if(e.ready()) {
System.out.println(e);
e.action();
eventList.remove(e);
--size;
}
}
}
}
The error java.util.ConcurrentModificationException
is thrown at the flag lined (Event e = it.next();
). Do you see a mistake in my code that makes obvious the reason of that exception to be thrown?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在修改
eventList
,同时使用eventList.remove()
进行迭代。您不能这样做,否则Iterator
将变得不可用。只需将
eventList.remove(e)
替换为it.remove()
就可以了。此外,如果其中一个事件在第一次运行时未准备好,您很容易陷入无限循环,因为
it.hasNext()
一旦返回就永远不会返回true
false
,但size
也不会被修改。一种解决方案是将整个Iterator it = ...
行移动到第一个while
循环的内部。我还会修改外部
while
循环以使用while (!e.isEmpty())
而不是尝试跟踪eventList
的大小手动。Your are modifying
eventList
while usingeventList.remove()
while iterating over it. You must not do this, or theIterator
becomes unusable.Simply replace
eventList.remove(e)
withit.remove()
and it should be fine.Also, you can easily run into an endless loop if one of your events isn't ready in the first run because
it.hasNext()
will never returntrue
once it returnedfalse
, butsize
won't be modified either. One solution would be to move the wholeIterator it = ...
line inside the firstwhile
loop.I'd also modify the outer
while
loop to usewhile (!e.isEmpty())
instead of trying to track the size ofeventList
manually.您应该通过迭代器删除元素,否则迭代器会因为底层集合发生更改而重置。
You should remove the element through the iterator, otherwise the iterator gets reset because the underlying collection changed.