为什么一个循环抛出一个ConcurrentModificationException,而另一个不抛出?

Jas*_*son 10 java iterator concurrentmodification

我在编写旅行推销员计划时遇到过这种情况.对于内循环,我尝试了一个

for(Point x:ArrayList<Point>) {
// modify the iterator
}
Run Code Online (Sandbox Code Playgroud)

但是当向该列表添加另一个点时会导致ConcurrentModicationException被抛出.

但是,当我将循环更改为

for(int x=0; x<ArrayList<Point>.size(); x++) {
// modify the array
}
Run Code Online (Sandbox Code Playgroud)

循环运行良好,没有抛出异常.

两个for循环,那么为什么一个抛出异常而另一个没有呢?

Mar*_*tin 9

正如其他人所解释的那样,迭代器检测对底层集合的修改,这是一件好事,因为它可能会导致意外行为.

想象一下这个修改集合的无迭代器代码:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 我选择了您的答案,因为您展示了与通过 get() 访问相比,在迭代时会出现什么问题 (2认同)

Jim*_*ler 6

第一个示例使用迭代器,第二个示例不使用迭代器.它是检查并发修改的迭代器.