【问题标题】:NullPointerException in the implementation of Doubly Linked List双向链表实现中的 NullPointerException
【发布时间】:2017-06-10 23:53:15
【问题描述】:

当我尝试使用 InsertFront() 方法添加对象时,我收到了 NullPointerException。 DList 代码为:

public class DList {
 protected DListNode head;
  protected int size;

protected DListNode newNode(Object item, DListNode prev, DListNode next) {
    return new DListNode(item, prev, next);
  }

public DList() {
    head=newNode(null,head,head);
    size=0;
  }


public void insertFront(Object item) {
     head.next.prev=newNode(item, head, head.next);
     head.next=head.next.prev;
     size++;
}

但是,一旦我将 DList 构造函数更改为以下内容,此错误就不再出现:

 public DList() {
        head=newNode(null,head,head);
        head.prev=head;
        head.next=head;
        size=0;
      }

现在,我明白分配 head.next 和 head.prev 值解决了问题;但是当我已经将“head”变量分配为构造函数第一行中的上一个和下一个节点时,我不明白需要单独说明这一点:

head=newNode(null,head,head);

请解释一下。

【问题讨论】:

    标签: java list data-structures collections nullpointerexception


    【解决方案1】:

    在初始构造函数中,这可能不是你认为的那样:

    head=newNode(null,head,head);
    

    注意head最初是null,所以调用实际上是这样的:

    head=newNode(null,null /*prev*/, null /*next*/);
    

    insertFront 中,您尝试引用head.next.prev,但由于head.nextnull,您会遇到异常。

    另一种思考旧构造函数的方法是将其分解为 2 行:

    DListNode temp=newNode(null,head,head); // remember that head is null here
    head=temp;
    

    方法参数在变量赋值之前被评估。

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2011-06-03
      • 2018-03-14
      • 1970-01-01
      • 2015-05-16
      • 2012-05-10
      • 2013-02-22
      • 1970-01-01
      相关资源
      最近更新 更多