只需在jdk1.8(我的是 jdk1.8.0_60) 中运行以下代码,结果是:
true
false
true,
Run Code Online (Sandbox Code Playgroud)
方法c2()返回false,为什么?
我只想了解运行时常量池。不是比较不同的字符串。
public static void main(String[] args) throws InterruptedException {
c1();
c2();
c3();
}
private static void c1() {
String s1 = new String("a") + new String("b");
s1.intern();
String s2 = "ab";
System.out.println(s1 == s2);
}
private static void c2() {
String s1 = new String("h") + new String("e");
s1.intern();
String s2 = "he";
System.out.println(s1 == s2);
}
private static void c3() {
String s1 = new String("e") + new String("h");
s1.intern();
String s2 = "eh";
System.out.println(s1 == s2);
}
Run Code Online (Sandbox Code Playgroud)
所有你在这里检测的是由你达到你的时间main的方法,"he"已经在常量池,但"ab"并"eh"没有。
因此,虽然c1和c3添加“新”的字符串当你调用常量池intern,在c2对现有的字符串由返回intern-所以,如果你改变你的代码
private static void c2() {
String s1 = new String("h") + new String("e");
s1 = s1.intern();
String s2 = "he";
System.out.println(s1 == s2);
}
Run Code Online (Sandbox Code Playgroud)
...你会看到打印出来的true。
或者,要制作c1print false,只需强制"ab"进入常量池以开始:
public static final String foo = "ab";
Run Code Online (Sandbox Code Playgroud)
现在"ab"在c1运行之前在常量池中,所以同样,s1.intern()不会向常量池添加任何内容,并且引用比较打印false.
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |