首页 > 解决方案 > Java - 将对象插入队列,但在 java 中出现异常,即使节点已初始化

问题描述

我是编程初学者。我一直在寻找解决空指针异常的方法。发生空指针异常是因为对象尚未初始化。但是,尽管我已经初始化了对象,但当我实现将对象的数据排入队列的代码时,就会发生这种情况。

下面是入队的代码

    public void addToList(Human human){
    //When the list is empty, insert the human data
    if(isEmpty()){
        Node temp = new Node(human);
        temp.setNext(this.head);
        this.head = temp;
        numNodes++;
    }
    else{
        Node current = this.head;
        //If the list is not empty, the new human data will be enqueued based on the priority
        //If the current data has a lower priority, temp data (new human) will be inserted into the queue first
        if(current.getHuman().getPriority() < temp.getHuman().getPriority()){

            temp.setNext(this.head);
            this.head = temp;
            numNodes++;
        }
        else{
            //If the current data has a higher priority , it will traverse the queue until there is space(current.next = null) for temp data to insert
            while (current.getNext() != null){
                current = current.getNext();
            }
            current.setNext(temp);
            temp = this.head;
            //temp.setNext(this.head);
            numNodes++;
        }
    }
}

不管优先级如何,即使我删除了优先级的代码,文件编译后也无法运行enqueue方法。

它向我展示了下面的空指针异常。

java.lang.NullPointerException: Cannot invoke "Node.setNext(Node)" because "<local2>" is null

Node类如下:

public class Node{
protected Node next;
protected Human human;

public Node(Human new_human){
    this.human= new_human;
    this.next = null;
}

public Node getNext(){
    return next;
}

public void setNext(Node new_next){
    this.next = new_next;
}

public Patient getHuman(){
    return human;
}

public void setHuman(Human hu){
    this.human= hu;
}

}

我做错什么了吗 ?我已经寻找解决方案,但仍然没有解决。潜在的问题应该是“temp.setNext(this.head)”,但是如果我已经做了“Node temp = new Node(human)”,就不应该有null。我想知道我的初始化是否不正确。我试过“this.head = new Node(human)”,但还是不行。

希望任何人都可以给我一些建议来解决这个问题。
非常感谢。

标签: javanullpointerexceptionqueue

解决方案


推荐阅读