gpt4 book ai didi

java - 就字符串池而言,字符串连接如何工作?

转载 作者:行者123 更新时间:2023-12-04 07:42:14 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





What is the Java string pool and how is "s" different from new String("s")? [duplicate]

(5 个回答)


去年关闭。



13: String a = "";
14: a += 2;
15: a += 'c';
16: a += false;
17: if ( a == "2cfalse") System.out.println("==");
18: if ( a.equals("2cfalse")) System.out.println("equals");
输出: equals 如果我错了,请纠正我...
在第 13 行一个新的 String对象被创建并且引用存储在 a . (a = "")
在第 14 行一个新的 String对象被创建并且引用存储在 a .上一个 String对象变得有资格进行垃圾收集(GC)。 (a = "2c")
在第 15 行一个新的 String对象被创建并且引用存储在 a .上一个 String对象变得有资格进行垃圾收集(GC)。 (a = "2cfalse")。
现在, String pool2cfalse 组成文字。因此,在第 17 行,不应该 a == "2cfalse"评估为 true因为它们都指向内存中的同一个对象?
但是,程序输出只是 == .我哪里做错了?请问谁能给我解释一下...

最佳答案

"2cfalse"仅在第 17 行添加到字符串池中,当您比较 a 时字面意思"2cfalse" .a 引用的实例在第 17 行之前没有添加到字符串池中,因此它与 "2cfalse" 的实例不同。文字。
如果您将调用添加到 a.intern ()就在第 17 行之前,a 引用的实例将被添加到池中(因为它尚未在池中),并且第 17 行中的条件将评估为真。
如果一个 String等于 "2cfalse"在调用 a.intern() 之前已经在池中,您必须将其分配回 a (即 a = a.intern(); )为了 a引用存储在池中的实例。

String a = "";
a += 2;
a += 'c';
a += false;
a.intern (); // or a = a.intern(); in case the pool already contains "2cfalse"
if ( a == "2cfalse") System.out.println("==");
if ( a.equals("2cfalse")) System.out.println("equals");
输出:
==
equals

关于java - 就字符串池而言,字符串连接如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67395574/

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