[英]Why are the results of of str == str.intern() for StringBuilder using append or not different?
All.I have a java code snippet like this: All.I有一个像这样的java代码片段:
String a = new StringBuilder("app").append("le").toString();
System.out.println(a.intern() == a);
String b = new StringBuilder("orange").toString();
System.out.println(b.intern() == b);
and this java code will output true,false. 这个java代码将输出true,false。 I wonder why.
我想知道为什么。 Thanks All.
谢谢大家。
In both cases, StringBuilder.toString()
creates a new string. 在这两种情况下,
StringBuilder.toString()
都会创建一个新字符串。
In the first case, String.intern()
finds that there's no string "apple" in the intern pool, so adds the provided one to the pool and returns the same reference - which is why it prints true
. 在第一种情况下,
String.intern()
发现实习池中没有字符串“apple”,因此将提供的字符串添加到池中并返回相同的引用 - 这就是它打印为true
。
In the second case, String.intern()
finds that there's already a string "orange" in the intern pool, so returns a reference to that - which is a different reference to b
, hence it prints false
. 在第二种情况下,
String.intern()
发现实习池中已经有一个字符串“orange”,因此返回对它的引用 - 这是对b
的不同引用,因此它打印为false
。
Note that if you had a line before the start of this code of: 请注意,如果您在此代码开头之前有一行:
System.out.println("apple");
then you'd see false
from the first comparison too, for the same reason. 那么你也会因为同样的原因从第一次比较中看到
false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.