【问题标题】:Java Iterator implementation compile error: does not override abstract method remove()Java Iterator 实现编译错误:不覆盖抽象方法 remove()
【发布时间】:2011-03-24 20:30:42
【问题描述】:

为什么会出现以下编译错误:

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 ;
    }

}

【问题讨论】:

  • 因为LRIterator is not abstract and does not override abstract method remove()

标签: java iterator


【解决方案1】:

Java 8

在 Java 8 中,remove method 具有抛出 UnsupportedOperatorException 的默认实现,因此在 Java 8 中代码编译良好。


Java 7 及以下

因为Iterator接口有一个叫做remove()的方法,你必须实现它才能说你已经实现了Iterator接口。

如果您实现它,则该类“缺少”方法实现,这仅适用于 abstract 类,即延迟的类实现子类的一些方法。

文档可能看起来令人困惑,因为它说remove() 是一个“可选操作”。这仅意味着您实际上不必能够从底层实现中删除元素,但您仍然需要实现该方法。如果您不想从底层集合中实际删除任何内容,您可以像这样实现它:

public void remove() {
    throw new UnsupportedOperationException();
}

【讨论】:

  • 只是一个附录:Eclipse 似乎也没有抱怨该方法,即使在 Java 7 模式下也是如此;如果编写应该在 IDE 内部和外部编译的代码,则应牢记这一点。
  • 如果 Eclipse 没有抱怨没有覆盖remove,那么你没有正确配置它。 IDE 和 javac 接受/拒绝完全相同的程序集,除非您偶然发现了编译器错误,但这对于像这样的简单程序来说非常罕见。
【解决方案2】:

你必须实现remove,因为它是Iterator接口定义的契约的一部分。

如果你不想实现它,那么让它抛出一个异常:

public void remove() {
    throw new UnsupportedOperationException();
}

【讨论】:

    【解决方案3】:

    ...因为您没有为remove() 提供定义,而Iterator 是一个接口,因此您必须为任何具体实现提供其所有功能的定义。

    但是,如果您不想支持该功能,则可以添加一个引发异常的方法:

    public void remove(){
        throw new UnsupportedOperationException();
    }
    

    【讨论】:

      【解决方案4】:

      Iterator 是一个接口,这意味着您应该实现所有方法

      public interface Iterator<E> {
          boolean hasNext();
          E next();
          void remove();
      }
      

      hasNext() 和 next() 你已经有了,所以只需添加 remove() 方法

      如果您没有任何想法,只需抛出适当的异常:

      public void remove() {
          throw new UnsupportedOperationException();
      }
      

      【讨论】:

        【解决方案5】:

        你必须添加一个

        public Object remove() {
          throw new RuntimeException ("I'm not going to implement it!!!");
        }
        

        【讨论】:

        • 真的无效吗?尴尬:)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多