6

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.

Community
  • 1
  • 1
user1817988
  • 237
  • 2
  • 5
  • 11

1 Answers1

14

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

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • itr.remove() produces the an error (btw I need to remove them individually using an interator). – user1817988 Nov 12 '12 at 13:34
  • Exception in thread "main" java.lang.IllegalStateException at java.util.LinkedList$ListItr.remove(Unknown Source) at section1.FlightQueue.clear(FlightQueue.java:44) at section1.FlightTest001.main(FlightTest001.java:22) – user1817988 Nov 12 '12 at 13:36
  • You need to call `itr.next()`, See update. – Reimeus Nov 12 '12 at 15:51
  • 1
    What's the running time of `itr.remove()`? – PlsWork Jan 17 '20 at 22:47
  • 1
    ListIterator.remove() runs in O(1). It is not explicitly mentioned in the [Javadoc] (https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html) but the [source code] (http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/share/classes/java/util/LinkedList.java) suggests so. Scroll to line 918 to see the implementation – Kimutai Apr 11 '20 at 12:38