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?
source to share
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
andlistIterator
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 Iteratorremove
oradd
, the iterator will throwConcurrentModificationException
.
source to share