加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么一个循环抛出一个ConcurrentModificationExceptio

发布时间:2020-12-14 05:08:18 所属栏目:Java 来源:网络整理
导读:我在编写旅行推销员计划时遇到了这个问题.对于内循环,我尝试了一个 for(Point x:ArrayListPoint) {// modify the iterator} 但是当向该列表添加另一个点时会导致ConcurrentModicationException被抛出. 但是,当我将循环更改为 for(int x=0; xArrayListPoint.s
我在编写旅行推销员计划时遇到了这个问题.对于内循环,我尝试了一个
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
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读