aps aps - 1 month ago 4
Java Question

How to modify a Collection while iterating using for-each loop without ConcurrentModificationException?

If I modify a Collection while iterating over it using for-each loop, it gives

. Is there any workaround?

mre mre

Use Iterator#remove.

This is the only safe way to modify a collection during iteration. For more information, see The Collection Interface tutorial.

If you also need the ability to add elements while iterating, use a ListIterator.