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
  • 5
  • 11
  • 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,977
  • 8
  • 87
  • 106
  • oh well thank you lol, works now. – user1817988 Nov 12 '12 at 14:10
  • 1
    you posted the same question an hour ago, you got the same response. Why posting it again??? – UmNyobe Nov 12 '12 at 14:16
  • The other question lead to this problem, I thought i would get a faster answer if I posted it as a new question. – user1817988 Nov 12 '12 at 15:23
  • @user1817988 and also, you have to accept an answer which you think has resolved your issue, i see you are new to SO. read here about how would accepting an answer help you http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – PermGenError Nov 12 '12 at 15:24
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
  • 346
  • 3
  • 13
0

Use clear() method of LinkedList

Pazonec
  • 1,549
  • 1
  • 11
  • 35
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,729
  • 10
  • 59
  • 55