Jeb Jeb - 9 days ago 5
Java Question

remove elements from CopyOnWriteArrayList

I am getting an exception when I try to remove elements from CopyOnWriteArrayList using an iterator.
I have noticed that it is documented


Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.


(from http://download.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html)

Now, surprisingly i can iterate it with foreach and use the remove() function . But then I get the famous bug - when trying to remove an item from a list using a for loop - you skip the element next to the removed element.
any suggestions then?

Answer

Iterate over the collection choosing all the elements you want to delete and putting those in a temporary collection. After you finish iteration remove all found elements from the original collection using method removeAll.

Would that work out for you? I mean, not sure if deletion logic is more complicated than that in your algorithm.

Comments