为什么 Java 的 concat() 方法什么都不做?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2818796/
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
Why does Java's concat() method not do anything?
提问by soma sekhar
This code:
这段代码:
String s = "TEST";
String s2 = s.trim();
s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
results in this output:
导致此输出:
S = TEST
S2 = TEST
BUILD SUCCESSFUL (total time: 0 seconds)
Why are "TEST" and "ING" not concatenated together?
为什么“TEST”和“ING”没有连接在一起?
采纳答案by nos
a String is immutable, meaning you cannot change a String in Java. concat()returns a new, concatenated, string.
String 是不可变的,这意味着您不能在 Java 中更改 String。concat()返回一个新的、连接的字符串。
String s = "TEST";
String s2 = s.trim();
String s3 = s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
System.out.println("S3 = "+s3);
回答by Jesper
Because String
is immutable - class String
does not contain methods that change the content of the String
object itself. The concat()
method returns a new String
that contains the result of the operation. Instead of this:
因为String
是不可变的——类String
不包含改变String
对象本身内容的方法。该concat()
方法返回一个String
包含操作结果的new 。取而代之的是:
s.concat("ING");
Try this:
尝试这个:
s = s.concat("ING");
回答by MatsT
I think what you want to do is:
我想你想做的是:
s2 = s.concat("ING");
The concat function does not change the string s, it just returns s with the argument appended.
concat 函数不会更改字符串 s,它只是返回附加了参数的 s。
回答by npinti
concat
returns a string, so you are basically calling concat without storing what it returns.
Try this:
concat
返回一个字符串,因此您基本上是在调用 concat 而不存储它返回的内容。尝试这个:
String s = "Hello";
String str = s.concat(" World");
System.out.println(s);
System.out.println(str);
Should print:
应该打印:
Hello
Hello World
回答by npinti
As String is immutable when concat() is called on any String obj as
当在任何字符串 obj 上调用 concat() 时,字符串是不可变的
String s ="abc"; new String obj is created in String pool ref by s
字符串 s="abc"; 新字符串 obj 是由 s 在字符串池 ref 中创建的
s = s.concat("def"); here one more String obj with val abcdef is created and referenced by s
s = s.concat("def"); 这里又创建了一个带有 val abcdef 的 String obj 并由 s 引用
回答by Furba
.concat()
method returns new concatenated value.
there you did s.concat("ING")
--> this gives return value "Testing". But you have to receive it in declared variable.
.concat()
方法返回新的连接值。你做了s.concat("ING")
——>这给出了返回值“测试”。但是你必须在声明的变量中接收它。
If you did s=s.concat("ING");
then the value of "s" will change into "TESTING"
如果你这样做了,s=s.concat("ING");
那么“s”的值将变成“TESTING”