码迷,mamicode.com
首页 > 其他好文 > 详细

遍历对象的list删除时报错问题。

时间:2015-09-14 20:57:05      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:


我们对一个对象的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();
                }
            }

 

遍历对象的list删除时报错问题。

标签:

原文地址:http://www.cnblogs.com/jinzhiming/p/4807981.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!