Java "pass-by-reference" or "pass-by-value"?
技术问答
244 人阅读
|
0 人回复
|
2023-09-12
|
一直以为 Java 使用pass-by-reference。
: p+ Y1 E8 e, u. D% b; S& t9 L
, }5 _. k; @. D+ G! Z! t. W8 d 解决方案: 0 \+ c5 M, m' s# ?6 s
Java 总是pass-by-value。不幸的是,当我们处理对象时,我们实际上是在处理它引用的对象句柄,这些句柄也是按值传递的。这种术语和语义很容易混淆许多初学者。3 [" M) ^: t ^6 w$ J; f
这样:
7 C) c# w: `! F% a2 }6 Hpublic 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}9 T+ v/ x; P# V) w% T' ^* `
在上面的例子中aDog.getName()还是会回来的"Max". 值aDog内main功能变化不大foo与Dog "Fifi"作为对象基准,由值传递。如果通过引用传递,则aDog.getName()inmain将"Fifi"调用 后返回foo。
: Z2 l6 O+ L- f- N& h7 A同样地:
. O6 }- o+ D& qpublic 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");}* m5 w: W1 U9 z* H5 g" }' l
在上述例子中,Fifi叫狗的名字,foo(aDog)因为对象的名称设置在foo(...). 任何操作都是foo执行上d对于所有的实际目的,它们都被执行了aDog,但它是不是变量值可以改变aDog本身。 |
|
|
|
|
|