Thursday, July 15, 2010

Removing while Iterating a Collection in Java

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: