可能的重复项:
链接列表迭代器删除
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)
不知道出了什么问题,它在第一个 itr.remove() 处显示错误。
从迭代器 API:
非法状态异常 - 如果下一个方法 尚未调用,或者已调用 remove 方法 在最后一次调用下一个方法之后
在调用 iterator.remove() 之前,您必须调用 iterator.next()。
while(itr.hasNext()){
itr.next(); //This would resolve the exception.
itr.remove();
}
只有在之前调用 next() 或 previous() 时,才能调用 itr.remove(),因为它会删除由这些方法返回的元素。
public void clear(){
flights.clear();
}
使用 LinkedList 的 clear() 方法
看看 Javadoc for ListIterator
.它特别指出:
IllegalStateException - neither next nor previous have been called,
or remove or add have been called after the last call to next or previous.
在.remove()
发布的代码片段之前,您需要一个.next()
。
干杯