我一直以为Java使用pass-by-reference. 但是,我读了一篇博客文章,声称Java使用pass-by-value. 我不认为我明白作者所做的区别。

什么是解释?


当前回答

Java 以值传输对象的参考。

其他回答

Java 以值复制参考,因此,如果您将其更改为另一个(例如,使用新)则参考不会在方法之外更改。

短篇小说:

非原始:Java通过参考值;原始:仅值。

结局。

现在,如果你想想想什么(1)意味着,想象你有一个类的苹果:

class Apple {
    private double weight;
    public Apple(double weight) {
        this.weight = weight;
    }
    // getters and setters ...

}

然后,当你将这个类的一个例子转移到主要方法:

class Main {
    public static void main(String[] args) {
        Apple apple = new Apple(3.14);
        transmogrify(apple);
        System.out.println(apple.getWeight()+ " the goose drank wine...";

    }

    private static void transmogrify(Apple apple) {
        // does something with apple ...
        apple.setWeight(apple.getWeight()+0.55);
    }
}

哦......但你可能知道这一点,你对当你做这样的事情时会发生什么感兴趣:

class Main {
    public static void main(String[] args) {
        Apple apple = new Apple(3.14);
        transmogrify(apple);
        System.out.println("Who ate my: "+apple.getWeight()); // will it still be 3.14? 

    }

    private static void transmogrify(Apple apple) {
        // assign a new apple to the reference passed...
        apple = new Apple(2.71);
    }


}

我在这里创建了一个专门为任何编程语言提出这些问题的条纹。

Java 也被提及,这里是简短的概述:

Java 通过它的参数值“值”是Java 唯一的方式将一个参数转换为一个方法,使用从所提供的对象作为参数的方法将改变对象,因为参考指向原始对象(如果该方法本身改变某些值)。

最短的答案:)

Java 有 pass-by-value (和 pass-reference-by-value.) C# 也有 pass-by-reference

在 C# 中,它是用“out”和“ref”的关键字实现的。

通过参考:变量以一种方式通过,以便在方法内部的重新分配,即使在方法之外也被反映出来。

下面是通过参考(C#)的例子,这个功能在Java中不存在。

class Example
{
    static void InitArray(out int[] arr)
    {
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] someArray;
        InitArray(out someArray);

        // This is true !
        boolean isTrue = (someArray[0] == 1);
    }
}

此分類上一篇: MSDN 圖書館(C#):通過 ref 和 out 的序列

此分類上一篇: MSDN 圖書館(C#):通過價值和参考

Java 总是通过值的论点,而不是参考。


让我们用一个例子来解释这一点:

public class Main {

     public static void main(String[] args) {
          Foo f = new Foo("f");
          changeReference(f); // It won't change the reference!
          modifyReference(f); // It will modify the object that the reference variable "f" refers to!
     }

     public static void changeReference(Foo a) {
          Foo b = new Foo("b");
          a = b;
     }

     public static void modifyReference(Foo c) {
          c.setAttribute("c");
     }

}

我将在步骤中解释这一点:

宣布一个参考名为Foo类型,并将其分配给一个新的Foo类型对象与属性“f”。Foo f =新Foo(“f”);从方法侧,一个Foo类型的参考名称A被宣布,它最初被分配为零。

我希望你现在明白如何通过对象作为论点在Java工作:)