java.util.ConcurrentModificationException 解决方法,删除集合元素的方式

解决方法1:

需要再定义一个List,用来保存需要删除的对象:
List delList = new ArrayList();
最后只需要调用集合的removeAll(Collection con)方法就可以了。

解决办法2:

使用iterator的remove方法

例如:

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<Integer> listA=new ArrayList<>();
        listA.add(1);
        listA.add(2);
        listA.add(3);
        listA.add(4);
        listA.add(5);
        listA.add(6);
        Iterator<Integer> it_b=listA.iterator();
        while(it_b.hasNext()){
            Integer a=it_b.next();
            if (a==4) {
                it_b.remove();
            }
        }
        for(Integer b:listA){
            System.out.println(b);
        }
    }
}

参考链接:https://www.cnblogs.com/loong-hon/p/10256686.html

posted @ 2023-03-16 15:19  小小羊儿  阅读(25)  评论(0编辑  收藏  举报