从一个ArrayList删除元素,如果他们在一个又一个present不提高ConcurrentModificationException的 [英] Remove elements from an Arraylist if they are present in another one without raising ConcurrentModificationException

查看:192
本文介绍了从一个ArrayList删除元素,如果他们在一个又一个present不提高ConcurrentModificationException的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是code:

Ledger obj = null;
MyUtilPojo obj1 = null;
Iterator it = toList.iterator();
while (it.hasNext()) {
    obj = (Ledger) it.next(); //after first iteration next here produce an error
    Iterator it1 = moreToList.iterator();
    while (it1.hasNext()) {
        obj1 = (MyUtilPojo) it1.next();
        if (obj.getId() == obj1.getKey()) {
            toList.remove(obj);                                
        }
    }
}

这引发错误 ConcurrentModificationException的,可有人能帮助?

This raise an error ConcurrentModificationException, can someone help?

推荐答案

当您修改列表(通过添加或删除元素),而穿越与迭代器列表时发生ConcurrentModificationException的。

ConcurrentModificationException occurs when you modify the list (by adding or removing elements) while traversing a list with Iterator.

    Ledger obj = null;
    MyUtilPojo obj1 = null;
    List thingsToBeDeleted = new ArrayList();

    Iterator it = toList.iterator();
    while (it.hasNext()) {
        obj = (Ledger) it.next();
        Iterator it1 = moreToList.iterator();
        while (it1.hasNext()) {
            obj1 = (MyUtilPojo) it1.next();
            if (obj.getId() == obj1.getKey()) {
                thingsToBeDeleted.add(obj);    // put things to be deleted                            
            }
        }
    }
    toList.removeAll(thingsToBeDeleted);

这篇关于从一个ArrayList删除元素,如果他们在一个又一个present不提高ConcurrentModificationException的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆