我可以更改传递给我的方法的String对象的值吗? [英] Can I change String object's value passed to my method?
问题描述
我发现了以下问题是Java的"pass-by-reference"吗?或按值传递"?.
我几乎阅读了所有内容,但仍无法找出想要 foo(-)
方法更改我的 String
方法应该怎么做.价值?(也许也没有参考,对我来说没关系).
I read almost all of it, but could not find out yet what should I do if I want the foo(-)
method, to change my String
's value? (maybe or not reference too, it doesn't matter to me).
void foo(String errorText){
errorText="bla bla";
}
int main(){
String error="initial";
foo(error);
System.out.println(error);
}
我想在控制台上看到 bla bla
.有可能吗?
I want to see bla bla
on the console. Is it possible?
推荐答案
由于当前已声明该方法,因此无法在 foo
中更改 errorText
的值.即使将字符串 errorText
的引用传递到 foo
中,Java String
都是不可变的-您无法更改它们.
You can't change the value of errorText
in foo
as the method is currently declared. Even though you are passing a reference of the String errorText
into foo
, Java String
s are immutable--you can't change them.
但是,您可以使用 StringBuffer
(或 StringBuilder
).这些类可以在您的 foo
方法中进行编辑.
However, you could use a StringBuffer
(or StringBuilder
). These classes can be edited in your foo
method.
public class Test {
public static void foo(StringBuilder errorText){
errorText.delete(0, errorText.length());
errorText.append("bla bla");
}
public static void main(String[] args) {
StringBuilder error=new StringBuilder("initial");
foo(error);
System.out.println(error);
}
}
其他解决方案是使用包装器类(创建一个类来保存您的String引用,并在 foo
中更改引用),或者仅返回字符串.
Other solutions are to use a wrapper class (create a class to hold your String reference, and change the reference in foo
), or just return the string.
这篇关于我可以更改传递给我的方法的String对象的值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!