Java通过价值,优势还是劣势?

nik*_*hil 0 java

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中解决这些问题?

Mar*_*ers 8

在Java中,如果您有引用类型,则引用按值传递.

在方法内部,您可以改变传递的对象,调用者将看到这些更改.