ctrlShiftBryan
ctrlShiftBryan

Reputation: 27740

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]);
}

Upvotes: 0

Views: 543

Answers (2)

Droo
Droo

Reputation: 3205

A side-caveat, the type of the original collection matters in this instance as well. For instance, Arrays.asList(new Integer[]{1, 2, 3}); strangely creates an UnmodifiableList, in which case you would need to instantiate an empty ArrayList perform newList.addAll(Arrays.asList(new Integer[]{1, 2, 3});.

Upvotes: 0

notnoop
notnoop

Reputation: 59299

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.

Upvotes: 6

Related Questions