Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedList iterator remove [duplicate]

Possible Duplicate:
Efficient equivalent for removing elements while iterating the Collection

private LinkedList flights;

....

public void clear(){

    ListIterator itr = flights.listIterator();

    while(itr.hasNext()){


        flights.remove(itr.next());

    }

}

....

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
    at java.util.LinkedList$ListItr.next(Unknown Source)
    at section1.FlightQueue.clear(FlightQueue.java:44)
    at section1.FlightTest001.main(FlightTest001.java:22)

Whats wrong with it? cant at all understand why the error is given, I am sure i have used the same code on arraylists or arrays and it has worked.

like image 691
user1817988 Avatar asked Nov 12 '12 13:11

user1817988


People also ask

How do you remove consecutive duplicates in a linked list?

Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43->60.

Does LinkedList accept duplicates?

Each element is stored as a node. The LinkedList can have duplicate elements because of each value store as a node. But there may be a situation when we want to store only unique elements in LinkedList and want to remove duplicates from linked list. We will discuss some ways that can remove duplicates from linked list.


1 Answers

You cannot remove an item from the collection directly while iterating through the elements as this will cause a ConcurrentModificationException. Iterator.remove() is the accepted safe way to modify a collection during iteration. To avoid seeing an IllegalStateException, make sure to call Iterator.next():

while (itr.hasNext()) {
   itr.next();
   itr.remove();
}

or as you simply wish to remove all elements in the Collection, you could use:

flights.clear();

See: Efficient equivalent for removing elements while iterating the Collection

like image 129
Reimeus Avatar answered Sep 18 '22 14:09

Reimeus