Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java LinkedList safest way to delete while iterating

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?

like image 446
Slow Trout Avatar asked Apr 18 '15 21:04

Slow Trout


People also ask

Can I remove element while iterating list Java?

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.

How do you delete while iterating?

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.

Why is LinkedList removing o1?

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) .


1 Answers

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 and listIterator 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 own remove or add methods, the iterator will throw a ConcurrentModificationException.

like image 176
aioobe Avatar answered Sep 27 '22 20:09

aioobe