开发者

Java Iterator implementation compile error: does not override abstract method remove()

Why do i get the following compile error:

LRIterator is no开发者_StackOverflow社区t abstract and does not override abstract method remove() in java.util.Iterator

Note, the implementation is for a linked list

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

In Java 8 the remove method has a default implementation that throws UnsupportedOperatorException so in Java 8 the code compiles fine.


Java 7 and below

Because the Iterator interface has a method called remove(), which you must implement in order to say that you have implemented the Iterator interface.

If you don't implement it the class is "missing" a method implementation, which is only okay for abstract classes, i.e., classes that defer implementation of some methods to subclasses.

The documentation may seem confusing as it says that remove() is an "optional operation". This only means that you don't have to actually be able to remove elements from the underlying implementation, but you still need to implement the method. If you don't want to do actually remove anything from the underlying collection you implement it like this:

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


You must implement remove because it is part of the contract defined by the Iterator interface.

If you don't want to implement it then make it throw an exception instead:

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


...because you're not providing a definition for remove(), and Iterator is an interface, so you must supply a definition for all of its functions for any concrete implementation.

You can, however, add a method that throws an exception if you don't want to support the functionality:

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


Iterator is an interface which means that you should implement all methods

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

hasNext() and next() you already have so just add remove() method

If you haven't any idea just throw appropriate exception:

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


You have to add a

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜