java - 迭代器接口(interface)

标签 java iterator linked-list iterable

我有一个大学作业,要求我实现一个实现 Iterator 接口(interface)的内部类。迭代器在单链表父类(super class)上工作。

目前我的内部类是这样的:

private class ListIterator implements Iterator<V>{

    Node temp;
    boolean nextCalled = false;

    ListIterator(Node fo){
        this.temp = fo;
    }

    @Override
    public boolean hasNext() {
        if(temp != null){
            return true;
        }
        return false;
    }

    @Override
    public V next() {
        nextCalled = true;
        return temp.getReprValue();
    }

    @Override
    public void remove() {
        if(nextCalled && hasNext()){
            nextCalled = false;
            removeElement(temp.getReprKey());
            temp = temp.getNext();
        }

    }

}

现在我的问题是 hasNext() 方法返回 true,即使列表实际上是空的。其他一切似乎都有效。我可能在某处忽略了一个逻辑缺陷,但我自己找不到。

最佳答案

更改了您的实现以反射(reflect)迭代器合约的需求。您需要记住,您需要能够遍历集合的所有元素,即 next() 应该从第一个元素开始,并且在每次调用之后它必须将当前的下一个元素更改为列表中的下一个元素,如果没有则抛出异常。

很高兴阅读 Iterator interface doc了解您需要实现它的方式并从那里开始。

private class ListIterator implements Iterator<V> {
    private Node next;
    private boolean alreadyDeleted = false;

    ListIterator(Node node){
        this.next = node;
    }

    @Override
    public boolean hasNext() {
        // because next is the current element. We need to iterate over all the elements
        // from the collection.
        return next != null;
    }

    @Override
    public V next() {
        if (next == null) {
           throw new NoSuchElementException();
        }

        Node current = next;

        this.next = current.getNext();
        this.alreadyDeleted = false; // it's better to try to elimate this state variable. You can try to do in another way, if yours removeElement returns something

        return current;
    }

    @Override
    public void remove() {
        if (alreadyDeleted || next == null) {
           throw new IllegalStateException();
        }
        removeElement(next.getReprKey());
        this.alreadyRemoved = true;
    }

}

关于java - 迭代器接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15365165/

相关文章:

java - LambdaConversionException 与泛型 : JVM bug?

c++ - 与容器无关的迭代器参数

java - servlet 过滤器映射重叠

python - 为什么我不能对相同的数据进行两次迭代?

c++ - 将映射中的对象(指针)输出到二进制文件

java - 复制链表...不使用克隆

c++ - 在双链表中插入节点

c - 单链表无法正确添加到开头

java - 获取键盘按键的字符串

java - 是否可以在 ie 中从 JavaScript 创建任意 Java 对象?