我一直认为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"
。值aDog
内main
未在功能改变foo
与Dog
"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
本身。