Question

If I use a linked list Iterator to find an element, does calling remove() cause the Iterator to traverse the list again? The code is below

//The list is LinkedList<String> list; and has already been populated

Iterator itar = list.iterator();

 while(itar.hasNext())
{
           if(itar.next().equalsIgnoreCase("Foo")) 
               itar.remove();
}
Was it helpful?

Solution

A LinkedList in Java is a doubly linked list, meaning each node has a reference to the next and previous in the list.

When the iterator does a remove, it has a reference to the current node and simply reassigns the references in the next and previous (updating the head and tail references for the list itself if needed).

So, no; there is no additional iteration performed.

Also worth noting is that Java is open source these days. You can view the source for LinkedList here with the code the iterator's remove() calls here

Edit to Add: As noted in the comments, an iterator for a singly-linked list implementation could easily keep track of the previous node it iterated over and perform the same operation.

OTHER TIPS

No, iterators always only iterate once even if you call remove().

Removing an item from a linked list updates the relevant pointers without requiring any further iterations.

No Iterator does not start from beginning but it will point to the next element if exist.I want to make you aware about one important thing of Iterator that they are "Fail Fast" means if a collection is modified by one of its methods after an iterator is created for that collection, the iterator immediately becomes invalid and operations performed with the iterator after this point throw ConcurrentModificationExceptions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top