为什么一个循环会抛出 ConcurrentModificationException,而另一个循环则不会?
我在编写旅行推销员程序时遇到了这个问题。对于内部循环,我尝试了一个
for(Point x:ArrayList<Point>) {
// modify the iterator
}
,但是当向该列表添加另一个点时,导致抛出 ConcurrentMominationException 。
但是,当我将循环更改为
for(int x=0; x<ArrayList<Point>.size(); x++) {
// modify the array
}
循环时,循环运行良好,没有引发异常。
两者都是 for 循环,那么为什么一个会抛出异常而另一个不会呢?
I've run into this while writing a Traveling Salesman program. For an inner loop, I tried a
for(Point x:ArrayList<Point>) {
// modify the iterator
}
but when adding another point to that list resulted in a ConcurrentModicationException
being thrown.
However, when I changed the loop to
for(int x=0; x<ArrayList<Point>.size(); x++) {
// modify the array
}
the loop ran fine without throwing an exception.
Both a for loops, so why does one throw an exception while the other does not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如其他人所解释的,迭代器检测对底层集合的修改,这是一件好事,因为它可能会导致意外的行为。
想象一下这个修改集合的无迭代器代码:
As others explained, the iterator detects modifications to the underlying collection, and that is a good thing since it is likely to cause unexpected behaviour.
Imagine this iterator-free code which modifies the collection:
第一个示例使用迭代器,第二个示例没有。它是检查并发修改的迭代器。
The first example uses an iterator, the second does not. It is the iterator that checks for concurrent modification.
第一个代码使用迭代器,因此不允许修改集合。您使用 x.get(i) 访问每个对象的第二个代码,因此不使用迭代器,因此允许修改
the first code is using an iterator so modifying the collection is not allowed. The second code you are accessing each object with x.get(i), so not using an iterator, modifications thus are allowed
当您在第一个示例中迭代列表时,您无法修改列表。在第二个例子中,您只需一个常规的
for
循环。You cannot modify a
List
while you are iterating over it which you are doing in the first example. In the second you simply have a regularfor
loop.如果您运行代码并观察,您会发现循环的第一次迭代工作正常,但第二次迭代会抛出 ConcurrentMominationException ,
因为
next()
方法检查元素的数量是否没有改变。有关详细说明,请参阅 http://javaadami.blogspot.com/2007 /09/enhanced-for-loop-and.html
If you run the code and observe you find that first iteration of the loop works fine but the second throws
ConcurrentModicationException
if is because
next()
method checks if the number of the elements did not change.For nice explanation see http://javaadami.blogspot.com/2007/09/enhanced-for-loop-and.html