0

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]);
}
ctrlShiftBryan
  • 27,092
  • 26
  • 73
  • 78
  • possible duplicate of [Java: Efficient Equivalent to Removing while Iterating a Collection](http://stackoverflow.com/questions/223918/java-efficient-equivalent-to-removing-while-iterating-a-collection) – McDowell May 09 '11 at 12:16

2 Answers2

6

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.

notnoop
  • 58,763
  • 21
  • 123
  • 144
0

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

Droo
  • 3,177
  • 4
  • 22
  • 26