zoukankan      html  css  js  c++  java
  • List遍历时删除遇到的问题

    这周在开发中遇到了一个以前没遇到的小Bug,在这里记录下来。

    List集合,我们平时都经常使用。但是,我在遍历List集合时,调用了List集合的remove方法来删除集合中的元素,简单的代码结构是这样:

    for(String x:list){
      if(x.equals("del"))
        list.remove(x);
    }
    但是,就是类似这样一个简单的小程序,在执行时,遇到了如下的异常信息:
    Exception in thread "main" java.util.ConcurrentModificationException
        at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
        at java.util.AbstractList$Itr.next(Unknown Source)
    当时很不理解。后来上网找资料,看牛人分析List的源码才发现原因,是因为调用List的remove方法后,使expectedModCount(表示对
    ArrayList修改次数的期望值,它的初始值为modCount)和modCount(是AbstractList类中的一个成员变量)导致的.具体解析,可以
    参考博客:http://www.cnblogs.com/dolphin0520/p/3933551.html。一步步的分析的很细致。同样,在博客中也给出了解决方案:那就是
    使用Iterator提供的remove方法,用于删除当前元素:
    public class Test {
      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)
                iterator.remove();   //注意这个地方
          }
      }
    }
     
     
  • 相关阅读:
    临界区,互斥量,信号量,事件的区别
    解决位图失真-SetStretchBltMode()
    Invalidate、RedrawWindow与UpdateWindow
    Shlwapi.h Shlwapi.dll 动态库
    C++ _access和_waccess的使用方法
    纯C++ 连接SQL Server2005 数据库读写操作的小例子
    测试代码执行时间的帮助类
    BUG: GetDC() ReleaseDC()引起的内存泄漏
    DebugView图文教程
    CreateFile函数详解
  • 原文地址:https://www.cnblogs.com/junjiang3/p/7425598.html
Copyright © 2011-2022 走看看