java – 为什么一个循环抛出一个ConcurrentModificationException,而另一个没有?

我在编写旅行推销员计划时遇到了这个问题.对于内循环,我尝试了一个
for(Point x:ArrayList<Point>) {
// modify the iterator
}

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

但是,当我将循环更改为

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

循环运行良好,不会抛出异常.

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

解决方法

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

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

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
  }
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...