我正在尝试使我的添加方法起作用,正如您从下面的代码中看到的那样,这给我找出代码出了什么问题带来了巨大的困难。
NodeFN 类:
public class NodeFN {
private String data; // Data for node.
private NodeFN next; // Next node.
public NodeFN(String data) {
this.data = data; // Take the data value passed in & store it in the data field.
this.next = null; // Take the next node & store it in the next field.
}
// Mutator functions.
public String getData() {return data;}
public NodeFN getNext() {return next;}
public void setData(String d) {data = d;}
public void setNext(NodeFN n) {next = n;}
}
队列类别:
public class Queue {
NodeFN head = null; // Head of node.
public String n;
public Queue() {} // Default constructor.
public Queue(String n) {
head = new NodeFN(n); // head is now an object of NodeFN which holds a string.
}
public void add(String n) {
NodeFN nn = new NodeFN(n); // nn is now an object of NodeFN which holds a string.
if(nn == null) { // If the new node (nn) is empty.
head = nn; // Then allow head to equal to the new node(nn).
} else {
// If new node (nn) alphabetically comes first compared to head
if(nn.getData().compareTo(head.getData()) < 0) {
nn.setNext(head);
head = nn;
}
}
}
public static void main(String[] args) {
Queue q = new Queue();
q.add("some string to test to see if it prints in console");
System.out.println(q);
}
}
最佳答案
让我们从这里开始:
NodeFN nn = new NodeFN(n);
if(nn == null) {
这两行放在一起没有意义。在 Java 中,第一行保证返回不 null 的内容。唯一可能发生的事情是:构造函数可能会抛出异常,但是您将永远到达下一行。
因此:你永远不会采用 if 的“then”分支。
然后:
if(nn.getData().compareTo(head.getData())
...仅当 head 为 != null 时才有效。
但令人惊讶的是:在队列类的两个构造函数中,只有第二个确保 head 为 != null。
长话短说:这就是 NullPointerException 的产生方式! 当你改变时
Queue q = new Queue();
至
Queue q = new Queue("whatever");
你的例子不应该再失败了。但当然,代码仍然有错误。修复的关键是:确保 head 已初始化;并确保在可能为 null 的情况下与 null 进行比较!
关于java - 使用 Java 节点构建我自己的队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40411294/