Java 迭代器 双向链表

3

你好,我非常新于Java编程,并且正尝试通过实现双向链表格式来创建一个Deque类。当我运行代码(DequeApp)时,我得到了一个NullPointerException,它指向我的Iterator.next(Deque.java:44)。

Error messages:  **Exception in thread "main" java.lang.NullPointerException
    at dlist.Deque$DoubleListIterator.next(Deque.java:44)



        public E next() {
                if (!hasNext()) {throw new NoSuchElementException();}
                else{
                E temp = current.item;
                current = current.next;
                return temp;}
            }

可能是Java双向链表迭代器的重复问题。 - Aakash
非常相似的代码(写链表的方法并不多...),@Aakash,尽管索引被正确地递增了。 - tucuxi
我知道算法应该是相同的,大多数实现也应该是相同的,但是OP在两个不同的地方问了同样的问题,遇到了同样的问题。他得到了NPE,而解决方案已经提供。虽然我标记了这个问题为重复,但我也自己给出了解决问题的方法。 - Aakash
是的,很抱歉我问了两次同样的问题,只是我没有完全理解另一篇帖子,对不起,我才刚开始学习Java,希望能变得更好,谢谢Aakash! - Robert
3个回答

3

我做了两个修改。

  1. As tucuxi already told, increment index.
  2. Start current from head, not head.next.

    private class DoubleListIterator implements Iterator<E> {
    // instance variable
    private Node current = head;
    private int index = 0;
    
    public boolean hasNext() {
        return index < N;
    }
    
    public E next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        } else {
            index++;
            E temp = current.item;
            current = current.next;
            return temp;
        }
    }
    
    public void remove() {
        throw new UnsupportedOperationException();
    }
    }
    

非常欢迎。但是@tucuxi说得对。养成调试习惯,确保一切都在应该的位置上。 - Aakash

2

你在DoubleListIterator中忘记了增加index计数器。你写成:

public E next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    } else {
        E temp = current.item;
        current = current.next;
        return temp;
    }
}

你应该已经写过了:

并且你应该已经写过了:

public E next() {
    if (!hasNext()) {
        throw new NoSuchElementException();
    } else {
        index ++; // <---- without this, hasNext() always returns true
        E temp = current.item;
        current = current.next;
        return temp;
    }
}

请注意,我已将缩进格式更改为Oracle指南的格式。
第二个错误是您初始化迭代器如下:
    private Node current=head.next;

然而,这使得无法检索 head (因为你已经指向了它的 next 节点)。并且使你的索引计数器偏离一个位置。更正后代码:

    private Node current=head;

嗨tucuxi,抱歉我仍然遇到相同的异常。线程“main”中的异常java.lang.NullPointerException 在dlist.Deque $ DoubleListIterator.next(Deque.java:46)中,这是第46行“E temp = current.item;”。 - Robert
1
在更上面发现了另一个错误。你应该使用调试器进行全面检查,确保一切看起来都很好;未经测试的代码总是在第一次运行时充满错误。 - tucuxi

0

除了使用索引变量之外,另一个选择是

也许你可以在hasNext中尝试使用"current.next != null"。

但如果已经使用索引没有问题的话,那就不用管它了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接