谁能解释这种奇怪的行为String?
这是我的代码:
String s2 = "hello";
String s4 = "hello"+"hello";
String s6 = "hello"+ s2;
System.out.println("hellohello" == s4);
System.out.println("hellohello" == s6);
System.out.println(s4);
System.out.println(s6);
Run Code Online (Sandbox Code Playgroud)
输出是:
true
false
hellohello
hellohello
Run Code Online (Sandbox Code Playgroud)
你需要知道之间的差异str.equals(other)和str == other.前者检查两个字符串是否具有相同的内容.后者检查它们是否是同一个对象."hello" + "hello"并且"hellohello"可以在编译时优化为相同的字符串."hello" + s2将在运行时计算,因此将是一个不同的新对象"hellohello",即使其内容相同.
编辑:我刚刚注意到你的标题 - 连同用户3580294的评论,似乎你应该已经知道了.如果是这样,那么唯一可能存在的问题是为什么一个被认为是常数而另一个不被认可.正如一些评论者所建议的那样,make s2final会改变行为,因为编译器可以s2以相同的方式信任"hello",并且可以"hello" + s2在编译时解析.
String s2 = "hello";
String s4 = "hello" + "hello"; // both "hello"s are added and s4 is resolved to "hellohello" during compile time (and will be in String pool)
String s6 = "hello"+ s2; // s6 is resolved during runtime and will be on heap (don't apply Escape analysis here)
Run Code Online (Sandbox Code Playgroud)
所以,
System.out.println("hellohello" == s4); // true
System.out.println("hellohello" == s6); // false
Run Code Online (Sandbox Code Playgroud)
"hello" + s2 像这样工作:
+操作者实际调用的StringBuilder#追加(字符串或多个)方法"hellohello" == s6实际上false.更多信息: