Java 代码:
private BiNode root = null;
//constructor
BST(int[] r) {
BiNode s = new BiNode(r[0], null, null);
test(root, s);
}
private void test(BiNode head, BiNode s){
head = s;
if (head != null)
System.out.println("head is not null");
if (root == null)
System.out.println("root is null");
}
输出:
head is not null
root is null
为什么root
不等于head
在 test
方法?
最佳答案
当您将构造函数中的 root
传递给方法 test
时,该方法实际上使用一个指向对象值的新指针,该指针为 null(root
的值)。因此,在该方法中,当您将 head
的值更改为 s
时,您不会对 root
的指针进行任何更改,该指针仍为 null,但 head
的值会发生变化。
这是一个java障碍,即你不能传递指针,并且你在java中所做的任何事情都无法解决这个问题,所以你必须直接设置root
。
关于java - 为什么我不能将传入的对象分配给方法中的新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36821610/