java - 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)”,但还是不行。
希望任何人都可以给我一些建议来解决这个问题。
非常感谢。
解决方案
推荐阅读
- doctrine - Symfony 4 如何渲染通过@OneToOne 或类似关系引用到另一个实体的属性
- three.js - 使用 Jasmine 在 Karma 中加载文件时出现问题
- android - Android Moshi:发展现状如何
- php - Aws-lambda-php 进程在完成请求之前退出
- android - FFmpeg concat 视频命令错误
- c# - 如何使用接口作为泛型参数?
- python - Python3 - 多处理变量不更新
- php - 卷曲 PHP http_code 返回 0 但浏览器返回 200
- c++ - if 语句和 --variable
- ionic-framework - 在ionic 3中检查我的区域圈内的纬度和经度