Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 933|回复: 0

java.util.ConcurrentModificationException

[复制链接]

该用户从未签到

发表于 2011-10-17 19:27:48 | 显示全部楼层 |阅读模式
用iterator遍历集合时要注意的地方:不可以对iterator相关的地方做添加或删除操作。

下面用List为例来说明为什么会报 ConcurrentModificationException  这个异常,其它集合类似可以自己思考。



public static void main(String[] args)
{
  List<String> set = new ArrayList<String>();
  set.add("a10001");
  set.add("a10002");
  set.add("a10003");
  set.add("a10004");
  set.add("a10005");
  set.add("a10006");
  set.add("a10007");
  
  List<String> del = new ArrayList<String>();
  del.add("a10003");
  del.add("a10004");
  del.add("a10005");
  
  for(String str : set)
  {
   if(del.contains(str))
   {
    set.remove(str);
   }
  }
}



运行这段代码的结果



Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at com.debug.Debug.main(Debug.java:28)



大家都知道for(String str : set) 这句话实际上是用到了集合的iterator() 方法

在iterator的时候是产生了一个List的内部类Itr

JDK源码

public Iterator<E> iterator() {
   return new Itr();
}

在new Itr()时有一个关键性的操作 

/**
  * The modCount value that the iterator believes that the backing
  * List should have.  If this expectation is violated, the iterator
  * has detected concurrent modification.
  */
int expectedModCount = modCount;



再回头看一下List 的 remove方法

public boolean remove(Object o) {
if (o == null) {
            for (int index = 0; index < size; index++)
  if (elementData[index] == null) {
      fastRemove(index);
      return true;
  }
} else {
     for (int index = 0; index < size; index++)
  if (o.equals(elementData[index])) {
      fastRemove(index);
      return true;
  }
        }
return false;
    }



private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // Let gc do its work
    }



再看一下 iterator.next()操作

public E next() {
            checkForComodification();
     try {
  E next = get(cursor);
  lastRet = cursor++;
  return next;
     } catch (IndexOutOfBoundsException e) {
  checkForComodification();
  throw new NoSuchElementException();
     }
}



final void checkForComodification() {
     if (modCount != expectedModCount)
  throw new ConcurrentModificationException();
}



相信看到这儿大家已经应该明白了为什么会出现在这个异常了。

总结:

  iterator 时 将expectedModCount = modCount 在remove()时 modCount++ 在next()时

if (modCount != expectedModCount)
  throw new ConcurrentModificationException();



一旦删除或添加元素后 modCount ,expectedModCount 这两个值就会不一致 当next时就会报ConcurrentModificationException




了解了原由,解决方案就很简单了 在遍历时用一个集合存放要删除的对象 在遍历完后 调用removeAll(Collection<?> c) 就OK了。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

GMT+8, 2024-5-5 19:39 , Processed in 0.366044 second(s), 46 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表