It is common to iterate list of elements. Check some conditions and remove some elements from list.
for (ChildClass childItem : parent.getChildList()) {
if (childItem.isRemoveCandidat()) {
parent.getChildList().remove(childItem);
}
}
But in this case java.util.ConcurrentModificationException is thrown.
What is the best program pattern in this case?
Use an
Iterator. If your list supportsIterator.removeyou can use it instead! It won’t throw the exception.Note: The
ConcurrentModificationExceptionis thrown when you have “started” iterating over a collection and modifies the list during the iteration time (eg in your case it doesn’t have anything todo with concurrency. You are using theList.removeoperation during the iteration and that is the same in this case..).Full example: