user3466773
user3466773

Reputation: 186

Null Pointers in my Queue (Link Lists)

Okay, I have this program almost done, but I'm lost at this point. I'm returning null pointers (it says on line 44 but that's just a while loop) and I need help fixing it please. I use a linked list to implement my queue, and my other two classes pass 100%, so the final class (CarQueue) is where the problem lies that is creating a Null Pointer.

    public class CarQueue<E> {

    private LinkNode<E> head;
    private LinkNode<E> tail;

    public CarQueue() {
        head = null;
        tail = null;
    }

    public CarQueue(E newData) {
        LinkNode<E> temp = new LinkNode<E>(newData, null);
        head = temp;
        tail = temp;
    }

    public void addToQueue(E newData) {
        LinkNode<E> temp = new LinkNode<E>(newData, null);
        if (empty() == false) {
            tail.setNext(temp);
            tail = temp;
        } else {
            head = temp;
            tail.setNext(temp);
            tail = temp;
        }
    }

    public String toString() {
        LinkNode<E> temp = head;
        String cars = "";
        while (temp.getNext() != null) {
            cars += temp.toString() + '\n';
        }
        return cars;
    }

    public E removeFmQueue() {
        LinkNode<E> headReturn = head;
        head = head.getNext();
        return headReturn.getData();

    }

    public LinkNode<E> peek() {
        return head.getNext();
    }

    public boolean empty() {
        if (head == null)
            return true;
        else
            return false;
    }
}

Upvotes: 0

Views: 425

Answers (1)

aliteralmind
aliteralmind

Reputation: 20163

If

while (temp.getNext() != null)  {

is the line throwing an exception, then temp is null, (or, if it's even possible, getNext() is throwing a NullPointerException). But let's assume temp is the problem.

temp is being assigned to head, so is head being assigned to null?

If the zero-parameter constructor is called, but no other functions are called before calling toString(), then this would indeed result in temp being assigned null. Therefore, when you attempt temp.getNext(), a NullPointerException is thrown.

To prevent this, you could have an alternative value returned by the toString() method:

public String toString()  {
   if(head == null)  {
      return  "no head. I got nothing.";
   }

   //print the other stuff...
}

But, really, the best solution is to never allow head--and therefore temp--to be null, as this means your class is in an unstable and basically-unusable state.

The most obvious way to prevent this is to eliminate the zero-parameter constructor--or alternatively have it only call the other constructor with a non-null value--and ensure that the other constructor never lets head remain as null.

Upvotes: 1

Related Questions