[英]Where does String s= s1+s2;(s1 & s2 are String literals) returns from? heap or pool
String s1="abc"; //pool
String s2="abccde"; //pool
String s3="cde"; //pool
String s4=s1+s3; //heap
String s5=new String("abccde"); //heap
System.out.println(s2==s4);
System.out.println(s4==s5);
System.out.println(s2==s5);
I was expecting false,true false BUT got all false in result. 我原本以为是假,但真是假,但结果都是假。 While i tried using .intern();
当我尝试使用.intern();时 in s4 i got true for s2==s4 meaning after intern();
在s4中,我对s2 == s4表示正确,这意味着在intern()之后; it returned from pool so earlier it was returning from heap, so why not s4==s5 is giving true?
它是从池中返回的,因此它较早时是从堆中返回的,那么为什么s4 == s5不为true?
Thanks 谢谢
Because new always creates a new object and has no chance of returning one from a pool? 因为new总是创建一个新对象并且没有机会从池中返回一个对象? It's a constructor, not a factory method like intern().
它是一个构造函数,而不是像intern()这样的工厂方法。
None of those will ever identity equal s5
, as you explicitly used the new
keyword. 就像您显式使用
new
关键字一样,这些标识符都不会等于s5
。
If the compiler can determine that s1
and s3
are literal constants, it will treat the concat as a literal constant . 如果编译器可以确定
s1
和s3
是文字常量,则它将concat视为文字常量 。 However, it is not a given that the compiler can make that determination. 但是,编译器可以做出确定的决定不是很明确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.