我可以在Java中通过引用传递参数吗? [英] Can I pass parameters by reference in Java?

查看:26
本文介绍了我可以在Java中通过引用传递参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要类似于 C#ref 关键字的语义.

I'd like semantics similar to C#'s ref keyword.

推荐答案

Java 令人困惑,因为一切都是按值传递.然而,对于引用类型的参数(即不是原始类型的参数),它是引用本身,它是按值传递的,因此它出现 传递引用(人们经常声称它是).事实并非如此,如下所示:

Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:

Object o = "Hello";
mutate(o)
System.out.println(o);

private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!

将打印 Hello 到控制台.如果你想让上面的代码打印Goodbye,选项是使用显式引用,如下所示:

Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:

AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }

这篇关于我可以在Java中通过引用传递参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆