简体   繁体   中英

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

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 (eg ArrayList ). In this particular case, it might be more efficient to simply clear the collection after the iteration.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM