![](/img/trans.png)
[英]Hashmap error is not abstract and does not override method in remove() in iterator
[英]Java Iterator implementation compile error: does not override abstract method remove()
為什么我會收到以下編譯錯誤:
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 ;
}
}
在Java 8中, remove
方法有一個拋出UnsupportedOperatorException
的默認實現,所以在Java 8中代碼編譯得很好。
因為Iterator
接口有一個名為remove()
的方法,您必須實現該方法才能說明您已經實現了Iterator
接口。
如果你沒有實現它,那么類就“缺少”一個方法實現,這對於抽象類來說是可以的,即將一些方法的實現推遲到子類的類。
文檔可能看起來令人困惑,因為它說remove()
是一個“可選操作”。 這只意味着您不必實際能夠從底層實現中刪除元素,但仍需要實現該方法。 如果您不想從底層集合中刪除任何內容,則可以像下面這樣實現:
public void remove() {
throw new UnsupportedOperationException();
}
...因為你沒有為remove()
提供定義,而Iterator
是一個接口,所以你必須為任何具體實現提供所有函數的定義。
但是,如果您不想支持該功能,則可以添加拋出異常的方法:
public void remove(){
throw new UnsupportedOperationException();
}
Iterator是一個接口,意味着您應該實現所有方法
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
你已經擁有hasNext()和next(),所以只需添加remove()方法即可
如果您不知道只是拋出適當的異常:
public void remove() {
throw new UnsupportedOperationException();
}
你必須添加一個
public Object remove() {
throw new RuntimeException ("I'm not going to implement it!!!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.