为什么我会收到以下编译错误:
LRIterator is not abstract and does not override abstract method remove() in java.util.Iterator
注意,实现是针对链表
public Iterator iterator()
{
return new LRIterator() ;
}
private class LRIterator implements Iterator
{
private DLLNode place ;
private LRIterator()
{
place = first ;
}
public boolean hasNext()
{
return (place != null) ;
}
public Object next()
{
if (place == null) throw new NoSuchElementException();
return place.elem ;
place = place.succ ;
}
}
Run Code Online (Sandbox Code Playgroud)
aio*_*obe 15
在Java 8中,该remove方法有一个默认实现,UnsupportedOperatorException在Java 8 中抛出代码编译得很好.
因为Iterator接口有一个被调用的方法remove(),您必须实现该方法才能说明您已经实现了Iterator接口.
如果你没有实现它,那么类就"缺少"一个方法实现,这对于抽象类来说是可以的,即将一些方法的实现推迟到子类的类.
文档可能看起来令人困惑,因为它说这remove()是一个"可选操作".这只意味着您不必实际能够从底层实现中删除元素,但仍需要实现该方法.如果您不想从底层集合中删除任何内容,则可以像下面这样实现:
public void remove() {
throw new UnsupportedOperationException();
}
Run Code Online (Sandbox Code Playgroud)