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);
我期待假的,真假的,但结果都是假的。当我尝试使用 .intern(( 时;在 S4 中,我在 intern(( 之后得到了 s2==s4 含义;它从池中返回,所以它更早地从堆返回,那么为什么 s4==s5 不是 true?
谢谢
因为 new 总是创建一个新对象并且没有机会从池中返回一个对象?它是一个构造函数,而不是像 intern(( 这样的工厂方法。
这些都不会等同于s5
,因为你明确使用了new
关键字。
如果编译器可以确定s1
和s3
是文本常量,则会将 concat 视为文本常量。但是,编译器无法做出该决定。