回答

收藏

Java "pass-by-reference" or "pass-by-value"?

技术问答 技术问答 243 人阅读 | 0 人回复 | 2023-09-12

一直以为 Java 使用pass-by-reference。# i- }/ ^, O* ?9 q2 U
                                                               
% I+ y4 N* i+ A6 d7 d    解决方案:                                                               
% ~5 k1 Q1 T1 s' r                                                                Java 总是pass-by-value。不幸的是,当我们处理对象时,我们实际上是在处理它引用的对象句柄,这些句柄也是按值传递的。这种术语和语义很容易混淆许多初学者。7 c; R4 h' t( g+ a! U
这样:' t' ~& J7 ], X: V: M& S7 U
    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}- g$ ?- g3 P3 ^2 ]+ G" z' U
在上面的例子中aDog.getName()还是会回来的"Max". 值aDog内main功能变化不大foo与Dog "Fifi"作为对象基准,由值传递。如果通过引用传递,则aDog.getName()inmain将"Fifi"调用 后返回foo。/ ^) G$ S2 T2 P* q7 @2 G5 z
同样地:4 n( k( X% H3 \+ }  K2 [4 j8 O" f
    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");}5 U, \4 p5 ?9 U8 e
在上述例子中,Fifi叫狗的名字,foo(aDog)因为对象的名称设置在foo(...). 任何操作都是foo执行上d对于所有的实际目的,它们都被执行了aDog,但它是不是变量值可以改变aDog本身。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则