java - 使用 Java 节点构建我自己的队列

标签 java queue

我正在尝试使我的添加方法起作用,正如您从下面的代码中看到的那样,这给我找出代码出了什么问题带来了巨大的困难。

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/

相关文章:

java - 链接 jquery 选择器。我将所有 anchor 放入一个变量中,然后我想使用 id 选择其中一个 anchor

java - 在 Java 中将字符串转换为数字

java - 我应该如何改进DFS Java实现来解决这个问题?

algorithm - 将事件队列用于类似 cron 的目的是不是一个坏主意?

javaee bean 验证@NotNull 不可继承

java - Android 从应用程序 A 向应用程序 B 发送通知

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

c - 队列 valgrind 错误

c++ - "Aborted (core dumped)"队列类dequeue方法出错

java - 带有 ListenerPort 的 V5 消息传递提供程序