30 java string string-interning
String文字的行为在下面的代码中非常混乱.
我可以理解第1行,第2行和第3行true
,但为什么是第4行false
?
当我打印两者的哈希码时,它们是相同的.
class Hello
{
public static void main(String[] args)
{
String hello = "Hello", lo = "lo";
System.out.print((Other1.hello == hello) + " "); //line 1
System.out.print((Other1.hello == "Hello") + " "); //line 2
System.out.print((hello == ("Hel"+"lo")) + " "); //line 3
System.out.print((hello == ("Hel"+lo)) + " "); //line 4
System.out.println(hello == ("Hel"+lo).intern()); //line 5
System.out.println(("Hel"+lo).hashCode()); //hashcode is 69609650 (machine depedent)
System.out.println("Hello".hashCode()); //hashcode is same WHY ??.
}
}
class Other1 { static String hello = "Hello"; }
Run Code Online (Sandbox Code Playgroud)
我知道==
检查引用相等性并在池中检查文字.我知道equals()
是正确的方法.我想了解这个概念.
我已经检查了这个问题,但没有解释清楚.
我希望得到一个完整的解释.
Joa*_*uer 26
每次编译时间常数表达式是类型String
将投入字符串池中.
基本上这意味着:如果编译器可以(轻松地)"计算" String
不运行程序的值,那么它将被放入池中(规则稍微复杂一些并且有一些极端情况,请参阅链接以上所有细节).
第1-3行中的所有字符串都是如此.
"Hel"+lo
是不编译时常量表达式,因为lo
是一个非恒定的可变的.
哈希码是相同的,因为String的hashCode仅取决于其内容.这是equals()
和的合同所要求的hashCode()
.