为什么两个字符串对象的串联引用不等于相同内容的字符串对象 [英] Why Concatenation of two string objects reference not equal to same content string object
问题描述
为什么 s3
和 s5
String
对象以下不同的是,当尝试在字符串池中创建 s5
时,它会检查内容 s3
已经具有相同的内容,因此 s5
引用字符串池中的 s3
对象。
Why below s3
and s5
String
objects are differ, When s5
try to created in String pool it checks content s3
already have same content so s5
refers s3
object in string pool. But my assumption is wrong, then any one correct me.
String s1="Buggy";
String s2="Bread";
String s3="BuggyBread";
String s4 = "Buggy"+"Bread";
String s5 = s1 + s2
System.out.println(s3==s4); // True
System.out.println(s3==s5); //false
推荐答案
-
String s4 = Buggy + Bread;
编译器足够聪明,可以意识到这是只是在 s3
中已引用的常量 BuggyBread
。换句话说, s4
引用与 s3
相同的 String
The compiler is smart enough to realize this is just the constant BuggyBread
which is already referenced in s3
. In other words, s4
references the same String
as s3
that is in the string pool.
字符串s5 = s1 + s2;
在这里,编译器会忠实地将变量内容转换为基于 StringBuilder
的串联,从而产生与<$ c有所不同的引用$ c> s3 。换句话说,这类似于:
Here the compiler faithfully translates to a StringBuilder
-based concatenation of the contents of the variables, which yields a difference reference than s3
. In other words, this is similar to:
StringBuilder sb = new StringBuilder(s1);
sb.append(s2);
String s5 = sb.toString();
这篇关于为什么两个字符串对象的串联引用不等于相同内容的字符串对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!