我一直认为Java使用传递引用。

但是,我看过几篇博客文章,声称不是(博客文章中说Java使用值传递)。

我不认为我能理解他们的区别。

有什么解释?

解决方案

Java总是按值传递。
不幸的是,我们根本不处理任何对象,而是处理称为引用(当然是通过值传递)的对象句柄。选择的术语和语义很容易使许多初学者感到困惑。

它是这样的:

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本身。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。