小编典典

Java "pass-by-reference" or "pass-by-value"?

javascript

我一直认为 Java 使用pass-by-reference。


阅读 232

收藏
2022-01-02

共1个答案

小编典典

Java 总是pass-by-value。不幸的是,当我们处理对象时,我们实际上是在处理称为引用的对象句柄,这些句柄也是按值传递的。这种术语和语义很容易混淆许多初学者。

它是这样的:

public static void main(String[] args) {
    Dog aDog = new Dog("Max");
    Dog oldDog = aDog;

    // we pass the object to foo
    foo(aDog);
    // aDog variable is still pointing to the "Max" dog when foo(...) returns
    aDog.getName().equals("Max"); // true
    aDog.getName().equals("Fifi"); // false
    aDog == oldDog; // true
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    // change d inside of foo() to point to a new Dog instance "Fifi"
    d = new Dog("Fifi");
    d.getName().equals("Fifi"); // true
}

在上面的例子中aDog.getName()仍然会返回"Max". 值aDogmain未在功能改变fooDog "Fifi"作为对象基准由值来传递。如果它是通过引用传递的,那么aDog.getName()inmain"Fifi"在调用 之后返回foo

同样地:

public static void main(String[] args) {
    Dog aDog = new Dog("Max");
    Dog oldDog = aDog;

    foo(aDog);
    // when foo(...) returns, the name of the dog has been changed to "Fifi"
    aDog.getName().equals("Fifi"); // true
    // but it is still the same dog:
    aDog == oldDog; // true
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    // this changes the name of d to be "Fifi"
    d.setName("Fifi");
}

在上面的例子中,Fifi是调用后的狗的名字,foo(aDog)因为对象的名字被设置在foo(...). 任何操作是foo执行上d是这样的,对于所有的实际目的,它们被执行的aDog,但它是不是可以改变变量的值aDog本身。

2022-01-02