我一直以为Java是通过引用传递的。
但是,我已经看到一些博客文章(例如,this blog)声称不是。
我不认为我能理解他们的区别。
有什么解释?
最佳答案
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()
中的main
在调用"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
本身的值。
关于java - Java是“按引用传递”还是“按值传递”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56708290/