0

I have been trying to create a deque in Java, but I get a nullpointer exception when I add a new node. Here is the helper class I use for the doubly-linked list:

private class Node {
    private Item item;
    private Node next;
    private Node prev;
}

Then I add nodes to the beginning of the list as follows:

    public void addFirst(Item item) {
    Node oldfirst = first;
    first = new Node();      
    first.prev = null;
    first.item = item;
    first.next = oldfirst;
    oldfirst.prev = first;        
    N++;
}

I get a NullPointer exception for the oldfirst.prev = first; line. Also, when I compile the code I get the following warning:

Warning: The field Deque2<Item>.Node.prev is never read locally

What might I be doing wrong?

Gautam
  • 7,444
  • 9
  • 61
  • 102

2 Answers2

0

The exception means that oldfirst is null. And you initialise it as Node oldfirst = first, so it means that first is null.

assylias
  • 297,541
  • 71
  • 621
  • 741
0

My guess is that when your deque is empty, first is null. Then when you assign first into oldFirst, that makes oldFirst null, and so trying to access prev is giving an NPE. Changing the access to:

if (oldFirst != null)
    oldfirst.prev = first;

should fix it.

Your warning is probably just because you're not atcually using prev yet in your deque, you're just setting it. Fun fact: with a deque, you don't need a doubly-linked list, so your prev variable is unlikely to ever be used. If you also want to support queuing with your deque down the road (similar to how LinkedList implements both Deque and Queue) then you'll need to keep prev.

Brian
  • 16,069
  • 5
  • 38
  • 64