views:

83

answers:

2

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]);
}
+6  A: 

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
well im actually using the command pattern so i cant use iterator remove.
ctrlShiftBryan
oh thanks! i can ill just override that too. :) you put me on the right path thanks
ctrlShiftBryan
Or copy the collection as you iterate.
Tom Hawtin - tackline
A: 

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