简体   繁体   English

为什么使用append或者不同的StringBuilder的str == str.intern()的结果?

[英]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.

相关问题 为什么这些字符串的 str == str.intern() 结果不同? - Why are the results of of str == str.intern() for these strings different? StringBuilder.append(String str)会发生一些疯狂的事情; - Something crazy happens with StringBuilder.append(String str); 为什么String.intern()方法返回两个不同的结果? - Why does the String.intern() method return two different results? 与使用两个append()语句相比,在StringBuilder的append()语句中进行串联连接是否会花费不同的执行时间? - Does concatenating in a StringBuilder append() statement take a different amount of execution time than using two append() statements? 为什么String.intern()在JDK8和JDK9下返回不同的结果? - Why does String.intern() return different results under JDK8 and JDK9? 为什么我使用String.intern()与在Java中传递String对象获得不同的结果? - Why do I get different results with String.intern() vs. passing String object in Java? StringBuilder-使用串联与在循环中使用append - StringBuilder - Using concatenation vs using append in loop 为什么StringBuilder append()比LinkedList add()快? - Why StringBuilder append() faster than LinkedList add()? 为什么在循环中使用“str.charAt(i) = str.charAt(i+1)”时出现错误 - Why am I getting error while using "str.charAt(i) = str.charAt(i+1)" in a loop 为什么StringBuilder.append时间复杂度为O(1) - Why StringBuilder.append time complexity is O(1)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM