Java LinkedList - safest way to delete on repeat

I recall a while ago (I think it was some kind of Java book) that the safest way to delete an item when iterating through a collection is using iterator.remove

.

 while(iterator.hasNext())
 {
    if(it.next().condition())
      iterator.remove();
 }

      

How can I not find this link and need a relative quick confirmation, can any java veteran confirm this?

+3


source to share


1 answer


This is the only legal way of structural change LinkedList

during iteration.

Any other way to remove an item from the linked list during iteration (if you're lucky) throw a ConcurrentModificationException

.



From the documentation :

The iterators returned by these classes iterator

and listIterator

work with an error: if the list is structurally modified at any time after the iterator has been created, in any way other than through the Iterator remove

or add

, the iterator will throw ConcurrentModificationException

.

+5


source







All Articles