【问题标题】:Java Iterator Doubly Linked listJava迭代器双向链表
【发布时间】:2015-07-14 20:55:16
【问题描述】:

您好,我对 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;}
            }

【问题讨论】:

  • 非常相似的代码(写链表的方法不多...),@Aakash,虽然索引在那里正确递增。
  • 我知道算法是一样的,大多数实现也是一样的,但是 OP 在 2 个不同的地方问了同样的问题,同样的问题。他正在获得已经提供解决方案的 NPE。虽然我已将问题标记为重复,但我自己也给出了问题的解决方案。
  • 是的,对不起,我问了两次这个问题,只是我没有完全理解另一个帖子,对不起,我才开始学习 java,希望能变得更好,谢谢 Aakash!

标签: java nullpointerexception doubly-linked-list deque


【解决方案1】:

另一个使用索引变量的选项是

也许您可以在 hasNext 中尝试“current.next != null”。

但如果它已经在使用索引就没有问题了。

【讨论】:

    【解决方案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,对不起,我仍然遇到同样的异常。 dlist.Deque$DoubleListIterator.next(Deque.java:46) 线程“main”java.lang.NullPointerException 中的异常是这一行“E temp = current.item;”
    • 进一步发现另一个错误。你真的应该用调试器做一个完整的过程,确保一切看起来都很好;未经测试的代码在第一次运行时总是充满错误。
    【解决方案3】:

    我做了两个改变。

    1. 正如 tucuxi 所说,增加索引。
    2. 从 head 开始当前,而不是 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 说的没错。养成调试习惯,确保一切都在他们应该在的地方。
    猜你喜欢
    • 2015-07-13
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    • 2016-01-22
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多