首页 > 编程语言 > 详细

Exception in thread "Thread-1" java.util.ConcurrentModificationException 异常原因和解决方法

时间:2018-07-23 17:50:38      阅读:176      评论:0      收藏:0      [点我收藏+]

注:参考博客:https://www.cnblogs.com/dolphin0520/p/3933551.html
1、单线程环境下的异常重现

    public static void main(String[] args)  {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(2);
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
            Integer integer = iterator.next();
            if(integer==2) {
                list.remove(integer);
                //iterator.remove();   //正确写法
            }
        }
    }

  在while(iterator.hasNext()) 循环遍历时,只允许删除ArrayList 内部的  elementData[ ] 的最后一个元素,而不允许从中间删除。
  在 iterator.next()  的源码中,会首先执行方法:checkForComodification();  该方法:

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

  只有当两个变量值相等时才不会报错。而 list.add(2)操作和 list.remove(integer); 操作会使 modCount++;   但是变量 expectedModCount 是内部类的 Itr 子类 的 变量,该子类的实例化方法是:list.iterator();  实例对象时赋初始值:
int expectedModCount = modCount;   所以,不允许在 while(iterator.hasNext())  循环方法内 有list.add(2)操作和 list.remove(integer);操作,否则会导致expectedModCount != modCount ,进而导致  throw new ConcurrentModificationException();


Exception in thread "Thread-1" java.util.ConcurrentModificationException 异常原因和解决方法

原文:https://www.cnblogs.com/yaohuiqin/p/9355874.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!