2016-04-24 18 views
1

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不在test方法等于head

+0

你从来没有设置'root'等于任何东西。研究按价值传递。 –

回答

0

当您在构造函数中将root传递给方法test时,该方法实际上使用一个指向该对象值的新指针,该值为null(root的值)。因此,在将head的值更改为s的方法中,您不会对root的指针进行任何更改,该指针仍然为空,但head的值发生更改。

这是一个java障碍,你不能通过指针,在java中你不能做任何事情都会绕过这个,所以你必须直接设置root

+0

我明白你的观点。如果我想在'test'中改变'root',我应该首先启动:'root = new BiNode(); ”。这样对吗? – learner

+0

不,即使发起它也不会改变一件事情。你必须直接赋值,所以你必须把'root = something'。你可以创建一个具有'root'字段的对象,然后将该对象传递给一个方法,并将该对象的字段更改为任何你想要的,但是这需要一些时间来详细说明,而我不明白你的目标是什么: ) – Sakamiai

相关问题