以下是代码:
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
,有人可以帮忙吗?
答案 0 :(得分:0)
这样的东西应该有用(在临时列表中构造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;
答案 1 :(得分:0)
在使用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);