Skip to content
Advertisement

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

We all know you can’t do the following because of ConcurrentModificationException:

JavaScript

But this apparently works sometimes, but not always. Here’s some specific code:

JavaScript

This, of course, results in:

JavaScript

Even though multiple threads aren’t doing it. Anyway.

What’s the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?

I’m also using an arbitrary Collection here, not necessarily an ArrayList, so you can’t rely on get.

Advertisement

Answer

Iterator.remove() is safe, you can use it like this:

JavaScript

Note that Iterator.remove() is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.

Source: docs.oracle > The Collection Interface


And similarly, if you have a ListIterator and want to add items, you can use ListIterator#add, for the same reason you can use Iterator#remove — it’s designed to allow it.


In your case you tried to remove from a list, but the same restriction applies if trying to put into a Map while iterating its content.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement