Java是按值传递的.如果我需要参考通行证怎么办?例如,在以下代码中,我需要一个引用传递机制.
public class BinaryTree {
public TreeNode root;
public BinaryTree(){
root = null;
}
public TreeNode insert(TreeNode temp,int x){
if(temp == null){
temp = new TreeNode();
temp.key = x;
temp.left = temp.right = null;
return temp;
}
if(temp.key > x)
temp.left = insert(temp.left,x);
else if(temp.key < x)
temp.right = insert(temp.right,x);
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
当insert被调用时root,我需要root为基准传递,从而改变它的值.但这不会发生在Java中,因为它是通过值传递的.在C/C++中,可以轻松实现上述目标.难道你不认为这是Java的缺点吗?如何在Java中解决这些问题?