我可以更改传递给我的方法的 String 对象的值吗?
我发现以下问题 Java 是“按引用传递”还是“按值传递” ?。
我几乎阅读了所有内容,但还不知道如果我想要 foo(-)
方法来更改我的 String
的 ,我该怎么办价值? (也许或不参考,这对我来说并不重要)。
void foo(String errorText){
errorText="bla bla";
}
int main(){
String error="initial";
foo(error);
System.out.println(error);
}
我想在控制台上看到 bla bla
。是否可以?
I found the following question Is Java "pass-by-reference" or "pass-by-value"?.
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);
}
I want to see bla bla
on the console. Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您无法更改
foo
中errorText
的值,因为该方法当前已声明。即使您将 StringerrorText
的引用传递给foo
,JavaString
也是不可变的——您无法更改它们。但是,您可以使用
StringBuffer
(或StringBuilder
)。这些类可以在您的foo
方法中编辑。其他解决方案是使用包装类(创建一个类来保存 String 引用,并更改
foo
中的引用),或者仅返回字符串。You can't change the value of
errorText
infoo
as the method is currently declared. Even though you are passing a reference of the StringerrorText
intofoo
, JavaString
s are immutable--you can't change them.However, you could use a
StringBuffer
(orStringBuilder
). These classes can be edited in yourfoo
method.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.使用方法的返回值或创建一个包装类。
让它返回值:
将值包装在对象中:
Either use the return value of the method or create a wrapper class.
Have it return the value:
Wrap the value in an object:
是的,您可以借助反射来更改此设置,但这违反规则。
Yes you can change this with help of reflections but its against rule.
字符串值是不可变的——所以一旦你得到一个值,你就只能使用它。
String values are immutable -- so once you get a value, you're stuck with it.
Java 语言对文字
String
进行了特殊处理;您的代码大致相当于:换句话说,您只是将本地引用 errorText 指向不同的 String 对象,这不会影响方法之外的任何内容。
但更一般地说,
String
是不可变的;没有办法修改它们。Literal
String
s are treated specially by the Java language; your code is roughly equivalent to:In other words, you're just pointing the local reference
errorText
at a differentString
object, which affects nothing outside the method.More generally, though,
String
s are immutable; there's no way to modify them.您可以重新分配字符串引用:
You can reassign the String reference: