我的队列中的空指针(链接列表)

时间:2014-03-27 01:59:05

标签: java nullpointerexception linked-list queue

好的,我已经完成了这个程序,但此时我已经迷失了。我正在返回空指针(它在第44行说,但这只是一个循环)我需要帮助修复它。我使用链表来实现我的队列,而我的其他两个类传递100%,所以最后一个类(CarQueue)就是创建空指针的问题所在。

    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;
    }
}

1 个答案:

答案 0 :(得分:1)

如果

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

是抛出异常的行,然后temp为空,(或者,如果可能的话,getNext()抛出NullPointerException)。但我们假设temp是问题所在。

temp被分配到headhead被分配到null了吗?

如果调用零参数构造函数,但在调用toString()之前没有调用其他函数,那么这确实会导致temp被赋值null。因此,当您尝试temp.getNext()时,会抛出NullPointerException

为了防止这种情况,您可以使用toString()方法返回一个替代值:

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

   //print the other stuff...
}

但是,实际上,最好的解决方案是永远不要让head - 因此temp - 为null,因为这意味着你的类处于一个不稳定且基本上无法使用的状态。

防止这种情况最明显的方法是消除零参数构造函数 - 或者让调用具有非null值的其他构造函数 - 并确保其他构造函数从不让头部保持为空。