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?
Something like that should work (constructs the new content for toList
in a temp list):
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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.