[英]Remove elements from an Arraylist if they are present in another one without raising ConcurrentModificationException
Here is the 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);
}
}
}
This raise an error ConcurrentModificationException
, can someone help? 这会引发错误
ConcurrentModificationException
,有人可以帮忙吗?
Something like that should work (constructs the new content for toList
in a temp list): 这样的事情应该起作用(在临时列表中构造
toList
的新内容):
final List<Ledger> target = new ArrayList<Ledger>();
for (final Ledger led : toList) {
for (final MyUtilPojo mup : moreToList) {
if (led.getId() != mup.getKey()) { // beware of !=
target.add(led);
}
}
}
toList = target;
ConcurrentModificationException occurs when you modify the list (by adding or removing elements) while traversing a list with Iterator. 当您使用Iterator遍历列表时(通过添加或删除元素)修改列表时,会发生ConcurrentModificationException。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.