字符串文字的行为令人困惑 [英] Behavior of String literals is confusing

查看:85
本文介绍了字符串文字的行为令人困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String literals的行为在下面的代码中非常混乱。

The behavior of String literals is very confusing in the code below.

我可以理解第1行,第2行和第3行是,但为什么第4行 false

I can understand line 1, line 2, and line 3 are true, but why is line 4 false?

当我打印哈希码时两者都是一样的。

When I print the hashcode of both they are the same.

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"; }

我知道 == 检查引用相等并在池中检查文字。我知道 equals()是正确的方法。我想理解这个概念。

I know that == checks for reference equality and check in the pool for literals. I know equals() is the right way. I want to understand the concept.

我已经检查了这个问题,但没有明确解释。

I already checked this question, but it doesn't explain clearly.

我希望得到完整的解释。

I would appreciate a complete explanation.

推荐答案

编译时常量表达式 类型为 String 将被放入String池中。

Every compile-time constant expression that is of type String will be put into the String pool.

基本上这意味着:如果编译器可以(轻松地)计算 String 的值而不运行该程序,然后它将被放入池中(规则稍微复杂一点,并有一些极端情况,请参阅上面的链接了解所有细节。)

Essentially that means: if the compiler can (easily) "calculate" the value of the String without running the program, then it will be put into the pool (the rules are slightly more complicated than that and have a few corner cases, see the link above for all the details).

对于第1-3行中的所有字符串都是如此。

That's true for all the Strings in lines 1-3.

Hel+ lo 编译时常量expres sion,因为 lo 是一个非常量变量。

"Hel"+lo is not a compile-time constant expression, because lo is a non-constant variable.

哈希码是相同的,因为 String的hashCode仅取决于其内容。这是 equals() hashCode()

The hash codes are the same, because the hashCode of a String depends only on its content. That's required by the contract of equals() and hashCode().

这篇关于字符串文字的行为令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆