Java永远不会通过引用传递,对吗?......对吗? [英] Java is NEVER pass-by-reference, right?...right?

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

问题描述


可能重复:

是Java传递参考?

我今天发现了一种不寻常的Java方法:

I found an unusual Java method today:

private void addShortenedName(ArrayList<String> voiceSetList, String vsName)
{
     if (null == vsName)
       vsName = "";
     else
       vsName = vsName.trim();
     String shortenedVoiceSetName = vsName.substring(0, Math.min(8, vsName.length()));
     //SCR10638 - Prevent export of empty rows.
     if (shortenedVoiceSetName.length() > 0)
     {
       if (!voiceSetList.contains("#" + shortenedVoiceSetName))
         voiceSetList.add("#" + shortenedVoiceSetName);
     }
}

根据我所读到的关于Java的行为的一切传递变量,复杂对象与否,这段代码应该什么都不做。那么......我在这里错过了一些东西吗?是否有一些微妙的东西丢失在我身上,或者这些代码是否属于thedailywtf?

According to everything I've read about Java's behavior for passing variables, complex objects or not, this code should do exactly nothing. So um...am I missing something here? Is there some subtlety that was lost on me, or does this code belong on thedailywtf?

推荐答案

正如Rytmis所说,Java传递引用按价值。这意味着您可以合法地在方法的参数上调用变异方法,但是您无法重新分配它们并期望值传播。

As Rytmis said, Java passes references by value. What this means is that you can legitimately call mutating methods on the parameters of a method, but you cannot reassign them and expect the value to propagate.

示例:

private void goodChangeDog(Dog dog) {
    dog.setColor(Color.BLACK); // works as expected!
}
private void badChangeDog(Dog dog) {
    dog = new StBernard(); // compiles, but has no effect outside the method
}

编辑: 在这种情况下,这意味着虽然 voiceSetList 可能因此方法而改变(可能会添加新元素)对它来说, vsName 的更改在方法之外是不可见的。为了避免混淆,我经常标记我的方法参数 final ,这使得它们不会被重新分配(意外或非意外)在方法内。这将使第二个例子完全无法编译。

What this means in this case is that although voiceSetList might change as a result of this method (it could have a new element added to it), the changes to vsName will not be visible outside of the method. To prevent confusion, I often mark my method parameters final, which keeps them from being reassigned (accidentally or not) inside the method. This would keep the second example from compiling at all.

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

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