我正在使用双端队列进行分配,我们遇到了一个问题,即对象引用在通过一个非常简单的方法传递后从节点中消失。
一些重要的定义:
class Node {
    String s;
    Node prev;
    Node next;
    ...
}
class Sentinel extends Node {
    Node prev;
    Node next;
   //Constructor uses that of Node
}
class Deque {
    Sentinel start;
    ...
}
我们正在编写的一种方法是根据给定的字符串从双端队列中删除一个节点。
在双端队列中:
public void removeSorted(String toRemove) {
    // System.out.println(this.start);
    // System.out.println(this.start.next);
    this.start.next.removeSorted(toRemove);
}
注释掉的 println 显示正确的 Sentinel 和 Node。
然后,在节点中:
public void removeSorted(String toRemove) {
    if (this.s.equals(toRemove)) {
        // System.out.println(this.prev);
        // System.out.println(this.prev.next);
        this.prev.next = this.next;
        this.next.prev = this.prev;
    } else if (this.s.compareTo(toRemove) > 0) {
        throw new RuntimeException("String does not exist in these nodes!");
    } else {
        this.next.removeSorted(toRemove);
    }
}
this.prev正如预期的那样,用于在第一次递归时输出 Sentinel的 println 。但是,this.prev.next 输出 null 而不是 Node。
此功能仅在尝试删除第一个节点时失败,直接在 Sentinel 之后。如果您尝试删除任何其他节点,它会正常工作,并且尝试调用this.prev.next会导致非空答案。
为什么在传递给函数时(立即)引用消失了,因为我们已经证明在调用函数之前引用就在那里?