Search code examples
javaiteratorcollectionsconcurrentmodification

How do you interate over a Collection<T> and modify its items without ConcurrentModificationException?


I need to do something like this...

Collection<T> myCollection; ///assume it is initialized and filled


for(Iterator<?> index = myCollection.iterator(); index.hasNext();)
{
    Object item = index.next();
    myCollection.remove(item);
}

Obviously this throws ConcurrentModificationException...

So I have tried this but doesn't does seem elegant/efficient and throws a Type safety: Unchecked cast from Object to T warning

Object[] list = myCollection.toArray();
for(int index = list.length - 1; index >= 0; index--) {
 myCollection.remove((T)list[index]);
}

Solution

  • You can just use iterator.remove():

    for(Iterator<?> index = myCollection.iterator(); index.hasNext();)
    {
        Object item = index.next();
        index.remove();
    }
    

    Beware that this may cause O(n^2) runtime for some datatypes (e.g. ArrayList). In this particular case, it might be more efficient to simply clear the collection after the iteration.