Reputation: 29
I am getting a NullPointerException when I attempt to add an object with InsertFront() method. The DList code is:
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:
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; 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=newNode(null,head,head);
Please explain.
Upvotes: 1
Views: 137
Reputation: 18155
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=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.
Another way to think of your old constructor is to decompose it into 2 lines:
DListNode temp=newNode(null,head,head); // remember that head is null here
head=temp;
The method arguments are evaluated before the variable assignment.
Upvotes: 1