gpt4 book ai didi

java - 在 java 字符串中使用 intern

转载 作者:搜寻专家 更新时间:2023-10-31 19:39:42 24 4
gpt4 key购买 nike

我试图理解 Java 的 String 类,但我很难理解下面描述的情况。

考虑以下示例片段:

String x = new String("Hey");
String y = "Hey";

如果我使用 bool = y == x.intern(); 变量 bool 将等于 true.

我的问题是:

当我做出这样的声明时:

String b = "h";
String a = b.intern + "ey";
boolean x = a == "hey";

x 的值将是 false 但当我制作 a = (b + "ey").intern( ); x 的值将为 true

为什么第二个例子中的 x = true 不会? 是因为第一个例子中的声明不一样吗?如果是,有什么区别?

最佳答案

用你的第一个例子:

String y = "Hey";

Java 会自动保留字符串字面量,例如 ( JLS section 3.10.5 ):

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.

因此,当您调用 x.intern() 时,您会得到 "Hey" 的实习副本,因此它们是相同的对象并且 == 返回 true

但是在第二个例子中,b.intern() 是一个在运行时计算的方法调用,Java 的串联运算符将返回一个新的 String(不是 interned ),它与字符串字面值 "hey"(已经实习)是不同的对象,因此 == 返回 false(不同的对象)。

编辑

要弄清楚字符串连接发生了什么,请转到 JLS Section 15.18.1 :

The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

The String object is newly created (§12.5) unless the expression is a compile-time constant expression (§15.28).

但是,b.intern() + "ey"; 不是编译时常量表达式,因此生成的 String 对象尚未被实习,并且 == 将检测到它与实习的 "hey" 是不同的对象。

关于java - 在 java 字符串中使用 intern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17821744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com