I remember from a while back (I think it was some Java book) that the safest way to delete an element while iterating through a collection is using iterator.remove
.
while(iterator.hasNext())
{
if(it.next().condition())
iterator.remove();
}
As I cannot find that reference and need a relative quick confirmation, can some java veteran confirm this?
An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown. A program that demonstrates this is given as follows.
If you want to delete elements from a list while iterating, use a while-loop so you can alter the current index and end index after each deletion.
A LinkedList consists of a chain of nodes; each node is separated allocated. And so while inserting, it's not necessary to traverse all the nodes. And that's why it has the complexity O(1) .
This is the only legal way to structurally modify a LinkedList
during iteration.
Any other way of removing an element from a linked list during iteration will (if you're lucky) throw a ConcurrentModificationException
.
From the documentation:
The iterators returned by this class's
iterator
andlistIterator
methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's ownremove
oradd
methods, the iterator will throw aConcurrentModificationException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With