問題描述
我在編寫旅行推銷員程序時遇到了這個問題.對于內部循環,我嘗試了
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
}
但是當向該列表添加另一個點時會引發 ConcurrentModicationException
.
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.
都是for循環,為什么一個會拋出異常而另一個不會呢?
Both a for loops, so why does one throw an exception while the other does not?
推薦答案
正如其他人解釋的那樣,迭代器檢測到對底層集合的修改,這是一件好事,因為它可能會導致意外行為.
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:
for (int x = 0; list.size(); x++)
{
obj = list.get(x);
if (obj.isExpired())
{
list.remove(obj);
// Oops! list.get(x) now points to some other object so if I
// increase x again before checking that object I will have
// skipped one item in the list
}
}
這篇關于為什么一個循環會拋出 ConcurrentModificationException,而另一個不會?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!