简体   繁体   English

双向链表实现中的NullPointerException

[英]NullPointerException in the implementation of Doubly Linked List

I am getting a NullPointerException when I attempt to add an object with InsertFront() method.当我尝试使用 InsertFront() 方法添加对象时,出现 NullPointerException。 The DList code is: 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++;
}

However, this error no longer shows up as soon as I change the DList constructor to this:但是,一旦我将 DList 构造函数更改为:

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

Now, I do understand that assigning the head.next & head.prev values solved the problem;现在,我明白分配 head.next 和 head.prev 值解决了问题; But I don't understand what was the need for stating this seperately when I already assigned the 'head' variable as the prev and next nodes in the 1st line of the constructor:但是当我已经将“head”变量分配为构造函数第一行中的 prev 和 next 节点时,我不明白需要单独说明这一点:

head=newNode(null,head,head);

Please explain.请解释。

In the initial constructor, this may not be doing what you think it is:在初始构造函数中,这可能不是您认为的那样:

head=newNode(null,head,head);

Note that head is null initially, so the call is really something like this:请注意, head最初为null ,因此调用实际上是这样的:

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

In insertFront you try to reference head.next.prev , but since head.next was null you get an exception.insertFront您尝试引用head.next.prev ,但由于head.nextnull您会收到异常。

Another way to think of your old constructor is to decompose it into 2 lines:考虑旧构造函数的另一种方法是将其分解为 2 行:

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

The method arguments are evaluated before the variable assignment.在变量赋值之前评估方法参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM