【问题标题】:How intern works in case of Concat实习生在 Concat 的情况下如何工作
【发布时间】:2017-10-08 08:55:23
【问题描述】:
String a = "x";
String b = a + "y";
String c = "xy";
System.out.println(b==c);

为什么会打印 false

根据我的理解,“xy”(即 a+“y”)将被实习,当创建变量 c 时,编译器将检查字符串常量池中是否存在文字“xy”,如果存在,它将分配相同的引用c.

注意:我不是在问 equals() 与 == 运算符。

【问题讨论】:

标签: java string constants pool


【解决方案1】:

如果一个字符串是通过连接两个字符串字面量形成的,它也将被实习。

String a = "x";
String b = a + "y"; // a is not a string literal, so no interning
------------------------------------------------------------------------------------------
String b = "x" + "y"; // on the other hand, "x" is a string literal
String c = "xy";

System.out.println( b == c ); // true

这是一个常见的Java字符串实习示例

class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";

        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}

class Other { static String hello = "Hello"; }

接着是它的输出

true
true
true
true
false
true

【讨论】:

    【解决方案2】:

    将分配给c"xy" 立即添加到字符串池(由intern 使用)的原因是因为该值在编译时是已知的。

    a+"y" 的值在编译时是未知的,而只有在运行时才知道。因为intern 是一项昂贵的操作,除非开发人员明确编码,否则通常不会这样做。

    【讨论】:

    • 感谢您的回复。好的,所以变量 b 将出现在堆栈中,而 c 将引用字符串常量池?
    • 从技术上讲,b 将引用堆中的字符串,否则是的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多