字符串比较混乱 [英] String comparison confused
问题描述
在继续之前:我知道我们应该使用.equals()来比较内容.我现在只是在讨论以下情况下的实际引用是否相同...
说我们有以下内容:
String str1 = "str";
String str2 = "string";
String str3 = "ing";
String str4 = str1 + str3;
str1 = str4;
String str5 = "string";
System.out.println(str1==str2);//false
我认为应该是正确的,因为在字符串池中,对字符串"的引用应该与str1和str2相同,现在都为"string".应该为true,但最终为 false .
I think it supposed to be true since in the String pool, the reference to "string" should be the same, as str1 and str2, now are both "string". It should be true, but ends up as false.
System.out.println(str1.intern()==str2.intern());//true
我尝试了此操作,这次它返回了 true .然后我尝试了:
I tried this, and it returned a true this time. Then I tried:
System.out.println(str1==str5);//false
System.out.println(str2==str5);//true
也 System.out.println("str" +"ing" =="string");//真
不是应该来自字符串池吗?有人可以帮忙解释一下吗?
Aren't the supposed to come from the String pool? Could someone help explain this a bit?
推荐答案
仅字符串 literals 和常量表达式可以得到保证.由于 str1 + str2
不是文字,因此,是否对结果进行求值取决于JVM.您可以通过调用 intern()
来强制使用它.
Only string literals and constant expressions are guaranteed to be pooled. Since str1 + str2
is not a literal, it's up to the JVM whether or not the result will be interned. You can force it via calling intern()
as you have already found out.
字符串文字是对类
String
(第4.3.1节,第4.3.3节)的实例的引用.
A string literal is a reference to an instance of class
String
(§4.3.1, §4.3.3).
此外,字符串文字总是引用类 String
的相同实例.这是因为使用方法 String.intern
将字符串文字(或更常见的是作为常量表达式的值的字符串(第15.28节))插入"以便共享唯一的实例./p>
Moreover, a string literal always refers to the same instance of class String
. This is because string literals – or, more generally, strings that are the values of constant expressions (§15.28) – are "interned" so as to share unique instances, using the method String.intern
.
您的第二个示例"str" +"ing"
是一个常量表达式,因此可以保证被内插.
Your second example, "str" + "ing"
, is a constant expression so it is guaranteed to be interned.
另请参见 的JavaDocString.intern
.
这是试图解释发生了什么.编写良好的代码可能永远都不应该依赖于此,而应始终使用 equals
方法.任何合理的JRE都会有类似的支票
This is an attempt to explain what is going on. Well-written code should probably never rely on this but always use the equals
method. Any reasonable JRE will have a check like
if (this == other)
return true;
非常靠近 String.equals
的顶部,因此从性能角度考虑,没关系.
very close to the top of String.equals
so performance wise, it shouldn't matter.
这篇关于字符串比较混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!