Let us say you have a list and you want to remove items while iterating through it if a certain condition satisfies.
for (Object object : listOfObjects) {
if (isConditionSatisfied) {
listOfObjects.remove(object);
}
}
What is wrong with this code above? Try it and you will get this,
Exception in thread "main" java.util.ConcurrentModificationException
You might want to do this instead,
Iterator<Object> iterator = listOfObjects.iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
if (isConditionSatisfied) {
iterator.remove();
}
}
Have a nice day.
No comments:
Post a Comment