Java iterator implementation compilation error: do not overwrite abstract method remove()

Why do I receive the following compilation errors:

Lriterator is not abstract and does not override Java util. Abstract method remove() in iterator

Note that the implementation is for linked lists

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

}

Solution

Java 8

In Java 8, the remove method has a default implementation that throws unsupported operatorexception, so the code compiles well in Java 8

Java 7 and below

Because the iterator interface has a method called remove (), you must implement this method to show that you have implemented the iterator interface

If you don't implement it, the class "lacks" a method implementation, which is OK for abstract classes, that is, classes that postpone the implementation of some methods to subclasses

The document may look confusing because it says remove () is an "optional operation" This only means that you don't have to be able to actually remove elements from the underlying implementation, but you still need to implement the method If you do not want to delete anything from the underlying collection, you can do so as follows:

public void remove() {
    throw new UnsupportedOperationException();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>