通过引用在Java中传递一个字符串? [英] Passing a String by Reference in Java?
本文介绍了通过引用在Java中传递一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我习惯做以下的 C
:
void main() {
String zText = "";
fillString(zText);
printf(zText);
}
void fillString(String zText) {
zText += "foo";
}
和输出是:
foo
不过,在Java中,这似乎并没有工作。我假设,因为字符串
对象是的复制的而不是按引用的通过。我以为是字符串对象,它们总是通过引用传递。
However, in Java, this does not seem to work. I assume because the String
object is copied instead of passed by referenced. I thought Strings were objects, which are always passed by reference.
这是怎么回事呢?
推荐答案
您有三个选项:
-
使用StringBuilder的:
Use a StringBuilder:
StringBuilder zText = new StringBuilder ();
void fillString(StringBuilder zText) { zText.append ("foo"); }
创建一个容器类并通过容器的实例,以你的方法:
Create a container class and pass an instance of the container to your method:
public class Container { public String data; }
void fillString(Container c) { c.data += "foo"; }
创建一个数组:
Create an array:
new String[] zText = new String[1];
zText[0] = "";
void fillString(String[] zText) { zText[0] += "foo"; }
从性能上看,StringBuilder的通常是最好的选择。
From a performance point of view, the StringBuilder is usually the best option.
这篇关于通过引用在Java中传递一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文