Java是“通过引用传递”吗?或“按值传递”?
我一直以为Java 传递参考。
I always thought Java was pass-by-reference.
但是,我看过几篇博文(例如,此博客)声称它不是。
However, I've seen a couple of blog posts (for example, this blog) that claim that it isn't.
我认为我不理解他们所做的区别。
I don't think I understand the distinction they're making.
解释是什么?
Java总是通过按值即可。不幸的是,他们决定将对象的位置称为引用。当我们传递一个对象的值时,我们将引用传递给它。这对初学者来说很困惑。
Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.
它是这样的:
public static void main(String[] args) {
Dog aDog = new Dog("Max");
// 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
}
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
。函数 foo
中的 main
中的值 aDog
未更改>使用 Dog
Fifi
作为对象引用按值传递。如果它是通过引用传递的,那么 main
中的 aDog.getName()
将返回拨打
。 foo
后,Fifi
In the example above aDog.getName()
will still return "Max"
. The value aDog
within main
is not changed in the function foo
with the Dog
"Fifi"
as the object reference is passed by value. If it were passed by reference, then the aDog.getName()
in main
would return "Fifi"
after the call to foo
.
同样:
public static void main(String[] args) {
Dog aDog = new Dog("Max");
foo(aDog);
// when foo(...) returns, the name of the dog has been changed to "Fifi"
aDog.getName().equals("Fifi"); // 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(...)$内设置的C $ C>。
本身(当 foo
在 d
上执行的任何操作都是这样的,出于所有实际目的,它们在 aDog d
更改为指向不同的 Dog
实例时除外喜欢 d =新狗(Boxer)
)。
In the above example, Fifi
is the dog's name after call to foo(aDog)
because the object's name was set inside of foo(...)
. Any operations that foo
performs on d
are such that, for all practical purposes, they are performed on aDog
itself (except when d
is changed to point to a different Dog
instance like d = new Dog("Boxer")
).