zoukankan      html  css  js  c++  java
  • 遍历对象的list删除时报错问题。


    我们对一个对象的list或者map进行删除操作时,可能会这么写

            for(Distributor distributor:distributorList){
                String distributorShort = distributor.getDistributorShort();
                if(!MyString.isNoEmpty(distributorShort)||distributorShort.toUpperCase().indexOf(queryDistributorNameShowDis)==-1){
                    distributorList.remove(distributor);
                }
            }


    但是执行时,会出现一个线程问题的异常 Exception in thread "main" java.util.ConcurrentModificationException ,不能这么删除

    这个异常产生的原因有几个。

    一是直接对集合调用删除操作而不是在枚举器上。

    二是不同的线程试图对集合进行增删操作的时候。

    解决办法就是用Iterator,就不会报这个异常了。

                Iterator<Distributor> it = distributorList.iterator();
                while(it.hasNext()){
                    Distributor distributor = it.next();
                    String distributorShort = distributor.getDistributorShort();
                    if(!MyString.isNoEmpty(distributorShort)||distributorShort.toUpperCase().indexOf(queryDistributorNameShowDis)==-1){
                        it.remove();
                    }
                }
  • 相关阅读:
    基于雪花算法的单机版
    Spring cloud gateway自定义filter以及负载均衡
    logback转义符与MDC
    录音地址文件保存
    maven加载本地jar
    ES Log4J配置信息
    java线程池
    openstreetmap的数据下载
    php更新版本后(路径更改后)要做的调整
    重启IIS
  • 原文地址:https://www.cnblogs.com/jinzhiming/p/4807981.html
Copyright © 2011-2022 走看看