简体   繁体   English

String s = s1 + s2;(s1和s2是字符串文字)从何处返回? 堆或池

[英]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 . 如果编译器可以确定s1s3是文字常量,则它将concat视为文字常量 However, it is not a given that the compiler can make that determination. 但是,编译器可以做出确定的决定不是很明确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在连接两个String s1和s2时,生成的输出String s3将在java中创建堆或常量池吗? - on concatenating two String s1 and s2, produced output String s3 will create in heap or constant pool in java? String s1 == String s2(true)但FieldOffset不同 - String s1 == String s2 (true) but FieldOffset is different Java 的 String 常量池在哪里,堆还是堆栈? - Where does Java's String constant pool live, the heap or the stack? 为什么哈希码对于String s1 =“cat”和String s2 = new String(“cat”)是相同的? - Why hash code is same for String s1= “cat” and String s2= new String(“cat”)? S1包含带有正则表达式的s2 - S1 contains s2 with regex 返回List的方法 <T> 带参数列表 <S1> ,列表 <S2> ,其中S1和S2延伸T. - Method returning a List<T> with parameters List<S1>, List<S2>, where S1 and S2 extends T 尝试设计一个函数:hasCheated(String s1,String s2,int N)求值 - Trying to design a function : hasCheated(String s1,String s2, int N) that evaluates 使用可比较或比较器接口使用String s1的顺序对String s2进行排序 - Sort String s2 using the order of String s1 using either of comparable or comparator interface 改进我的Java方法containsSubstring(s1,s2),它查找s2是否为s1的子字符串 - Improving my Java method containsSubstring(s1, s2) which finds if s2 is a substring of s1 为什么选择System.out.println(“嘿s1 == s2:”+ s1 == s2); 打印“false”作为输出而不是打印“hey s1 == s2:false” - Why System.out.println(“hey s1==s2:”+s1==s2); prints “false” as the output instead of printing “hey s1==s2:false”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM