函数中的 Java 字符串值更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3486393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:13:00  来源:igfitidea点击:

Java string value change in function

javastringfunctionpass-by-reference

提问by Yura

I have this very awkward question...

我有一个非常尴尬的问题......

void changeString(String str){
    str = "Hello world":
}

main(){
    String myStr = new String("");
    changeString(myStr);
}

When mainreturns, the value is still ""and not "Hello world". Why is that?

main返回时,该值仍然"""Hello world"。这是为什么?

Also, how do I make it work? Let's say I want my function changeStringto change the string it got to "Hello world".

另外,我如何使它工作?假设我希望我的函数changeString将它得到的字符串更改为“Hello world”。

采纳答案by NullUserException

Everyone explained why it doesn't work, but nobody explained how to make it work. Your easiest option is to use:

每个人都解释了为什么它不起作用,但没有人解释如何使它起作用。您最简单的选择是使用:

String changeString() {
    return "Hello world";
}

main() {

    String myStr = new String("");
    myStr = changeString();
}

Although the method name is a misnomer here. If you were to use your original idea, you'd need something like:

尽管这里的方法名称用词不当。如果您要使用最初的想法,则需要以下内容:

void changeString(ChangeableString str) {
    str.changeTo("Hello world");
}

main() {

    ChangeableString myStr = new ChangeableString("");
    changeString(myStr);
}

Your ChangeableStringclass could be something like this:

你的ChangeableString班级可能是这样的:

class ChangeableString {
    String str;

    public ChangeableString(String str) {
        this.str = str;
    }

    public void changeTo(String newStr) {
        str = newStr;
    }

    public String toString() {
        return str;
    }
}


A quick lesson on references:

关于参考的快速课程:

In Java method everything is passed by value. This includes references. This can be illustrated by these two different methods:

在 Java 方法中,一切都是按值传递的。这包括参考。这可以通过这两种不同的方法来说明:

void doNothing(Thing obj) {
    obj = new Something();
}

void doSomething(Thing obj) {
    obj.changeMe();
}

If you call doNothing(obj)from main()(or anywhere for that matter), objwon't be changed in the callee because doNothingcreates a new Thingand assigns that new reference to objin the scope of the method.

如果您doNothing(obj)main()(或就此而言的任何地方)obj调用,则不会在被调用者中更改,因为doNothing创建了一个 newThing并将该新引用分配给obj了方法的范围内

On the other hand, in doSomethingyou are calling obj.changeMe(), and that dereferences obj- which was passed by value - and changes it.

另一方面,在doSomething您调用obj.changeMe(), 并且取消引用obj- 通过值传递 - 并更改它。

回答by starblue

Java uses a call by valuestartegy for evaluating calls.

Java 使用按值调用开始来评估调用。

That is, the value is copied to str, so if you assign to strthat doesn't change the original value.

也就是说,值被复制到str,所以如果你分配给str它不会改变原始值。

回答by Prasoon Saurav

Because the reference myStris passed by value to the function changeStringand the change is not reflected back to the calling function.

因为引用myStr是按值传递给函数的changeString,而更改不会反映回调用函数。

P.S : I am not a Java guy.

PS:我不是Java人。

回答by Johannes Wachter

If the changing of your Stringhappens very often you could also assign a StringBufferor StringBuilderto your variable and change its contents and only convert it to a Stringwhen this is needed.

如果String经常更改您的变量,您还可以将 aStringBuffer或分配StringBuilder给您的变量并更改其内容,并仅String在需要时将其转换为 a 。

回答by Aaron Novstrup

Expanding a bit on NullUserException's excellent answer, here's a more general solution:

扩展一下NullUserException 的优秀答案,这是一个更通用的解决方案:

public class Changeable<T> {
   T value;

   public Changeable(T value) {
      this.value = value;
   }

   public String toString() {
      return value.toString();
   }

   public boolean equals(Object other) {
      if (other instanceof Changeable) {
         return value.equals(((Changeable)other).value);
      } else {
         return value.equals(other);
      }
   }

   public int hashCode() {
      return value.hashCode();
   }
}

Yura's original code can then be rewritten as:

Yura 的原始代码可以改写为:

void changeString(Changeable<String> str){
   str.value = "Hello world":
}

void main() {
   Changeable<String> myStr = new Changeable<String>("");
   changeString(myStr);
}

And, just for fun, here it is in Scala:

而且,只是为了好玩,它在Scala 中

class Changeable[T](var self: T) extends Proxy;

object Application {
   def changeString(str: Changeable[String]): Unit = {
      str.self = "Hello world";
   }

   def main(): Unit = {
      val myStr = new Changeable("");
      changeString(myStr);
   }
}

回答by portforwardpodcast

Bill, I have a solution to your problem which uses a List as a pointer in java!

比尔,我有一个解决你的问题的方法,它在 Java 中使用 List 作为指针!

void changeString(List<String> strPointer ){
    String str = "Hello world";
    strPointer.add(0, str);
}

main(){
    LinkedList<String> list = new LinkedList<String>();
    String myStr = new String("");
    changeString(list);
    myStr = list.get(0);
    System.out.println( myStr );
}

This answer takes a little extra work to insert and get out the string from the list, however the final line will print "Hello world!"

这个答案需要一些额外的工作来插入和从列表中取出字符串,但是最后一行将打印“Hello world!”

I hope this can help others as well!

我希望这也能帮助其他人!

-Port Forward Podcast

-端口转发播客