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 supports Iterator.remove you can use it instead! It won't throw the exception.
Iteartor<ChildClass> it = parent.getChildList().iterator();
while (it.hasNext())
if (it.next().isRemoveCandidat())
it.remove();
Note: The ConcurrentModificationException is 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 the List.remove operation during the iteration and that is the same in this case..).
public static void main(String[] args) {
List<Integer> list = new LinkedList<Integer>();
list.add(1);
list.add(2);
list.add(3);
for (Iterator<Integer> it = list.iterator(); it.hasNext(); )
if (it.next().equals(2))
it.remove();
System.out.println(list); // prints "[1, 3]"
}
another option is:
for(int i = parent.getChildList().length - 1; i > -1; i--) {
if(parent.getChildList().get(i).isRemoveCandidat()) {
parent.getChildList().remove(i);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With