为什么我不能将传入的对象分配给方法中的新值?

时间:2016-04-24 09:52:27

标签: java methods

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

1 个答案:

答案 0 :(得分:0)

当您将构造函数中的root传递给方法test时,该方法实际上使用了一个指向对象值的新指针,该值为null(root的值)。因此,在您将head的值更改为s的方法中,您没有对root的指针进行任何更改,该指针保持为空,但head为价值变化。

这是一个java障碍,你无法传递指针,你在Java中无能为力,所以你必须直接设置root