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();   //注意这个地方
          }
      }
    }
     
     
  • 相关阅读:
    UrlRewriter配置IIS支持伪静态
    Linux 安装PAE内核
    Tmux入门教程
    Tmux与Oh-my-zsh环境整合
    MySQL Route负载均衡与读写分离Docker环境使用
    MySQL数据表的基本操作
    Git安全配置
    GitLab使用自定义端口
    Gitlab搭建安装及使用中遇到的问题。
    执行Docker命令报错解决办法
  • 原文地址:https://www.cnblogs.com/junjiang3/p/7425598.html
Copyright © 2011-2022 走看看