0

Possible Duplicate:
LinkedList iterator remove

private LinkedList flights;

...

public FlightQueue() {
    super();
    flights = new LinkedList();
}

...

public void clear(){

   ListIterator itr = flights.listIterator();

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

....

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)

No idea whats wrong, its showing the error at the first itr.remove().

Community
  • 1
  • 1
user1817988
  • 237
  • 2
  • 4
  • 10
  • 1
    same as [1 hour ago](http://stackoverflow.com/questions/13344447/linkedlist-iterator-remove) – jlordo Nov 12 '12 at 14:12

4 Answers4

6

From the iterator API:
IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method

you have to call iterator.next() before calling iterator.remove().

    while(itr.hasNext()){
        itr.next(); //This would resolve the exception.
        itr.remove();
    }
PermGenError
  • 45,111
  • 8
  • 85
  • 106
0

You can call itr.remove() only if you called next() or previous() before, because it removes an element that was returned by those methods.

public void clear(){
    flights.clear();
}
Kalicz
  • 344
  • 2
  • 13
0

Use clear() method of LinkedList

Pazonec
  • 1,529
  • 11
  • 34
0

Have a look at the Javadoc for ListIterator. It specifically states:

IllegalStateException - neither next nor previous have been called, 
or remove or add have been called after the last call to next or previous.

You'll need a .next() before the .remove() in your posted code fragment.

Cheers,

Anders R. Bystrup
  • 15,324
  • 10
  • 61
  • 54