Removing while iterating in Java

05 Nov 2010. comments

Have you ever tried to remove elements from a collection while iterating over it in java? This won’t work:

for(Foo foo : foos) {  

A ConcurrentModificationException will be thrown because you’re attempting to modify the list during iteration. It makes sense because if you remove something the list is in a new state and you can’t know what the next element should be after having removed one.

There is however a solution and it involves a commonly used pattern called an iterator. An iterator provides keeps track of an index as you traverse which allows it to give you a next element even if ones have been removed (because it is based on the original indexing). This allows you to manipulate whatever list you’re iterating over because your iteration doesn’t rely on the list’s current state.

Here is the above example reworked to use an iterator:

for (Iterator i = foos.iterator(); i.hasNext(); Foo foo = {  

The remove() option on the iterator removes the element from the underlying collection, but doesn’t impact the iterator.


Tagged: java C# C++

2018 Ben Lakey

The words here do not reflect those of my employer.