週末跟一個題友討論這段代碼會創建幾個對象。
String s = new String("xyz");
答案是我在網上看到的,覺得應該是對的,就錄上去了。
兩個或一個第一次調用 new String("xyz"); 時,會在堆內存中創建一個字符串對象,同時在字符串常量池中創建一個對象
"xyz"第二次調用 new String("xyz"); 時,只會在堆內存中創建一個字符串對象,指向之前在字符串常量池中創建的 "xyz"
然後有題友就在小程序裏給我留言,貼了段代碼,爲了說明問題,我把它做了修改。
String s = new String("2");
s.intern();
String s2 = "2";
System.out.println(s == s2);
String s3 = new String("1") + new String("1");
s3.intern();String s4 = "11";
System.out.println(s3 == s4);
JDK 1.8 的打印值
false
true
表面看上去:
第 1 個 false 很好理解,常量和對象地址不相等。
那爲啥第 2 個返回的是 true ?而把 s3.intern(); 這行代碼去掉,卻返回 false,這就很怪異。
於是乎,翻了 String intern() 方法的作用
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class {@code String}.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this {@code String} object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this {@code String} object is added to the
* pool and a reference to this {@code String} object is returned.
* <p>
* It follows that for any two strings {@code s} and {@code t},
* {@code s.intern() == t.intern()} is {@code true}
* if and only if {@code s.equals(t)} is {@code true}.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
大致意思就是,如果常量池有 equal 的字符串就返回常量池這個,如果沒有就把這個字符串對象添加進常量池,返回這個對象的引用。所有字符串字面量和字符串值常量表達式都是 interned。
JDK 1.8 關於這塊的說明文檔在這裏:
https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5
先看這段代碼內存變化
String s = new String("2");
s.intern();
String s2 = "2";
System.out.println(s == s2);
new String("2"); 會同時在常量池和堆中創建兩個對象,畫個圖幫助理解
再來看這段代碼
String s3 = new String("1") + new String("1");
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);
String s3 = new String("1") + new String("1");
是通過 StringBuilder 實現字符串相加,javap 查看彙編指令
執行後的內存示意圖如下
s3.intern();
String s4 = "11";
執行後,按照 API 的描述, s3.intern() 會把 s2 字符串對象添加到常量池返回引用,內存示意圖如下
看到這裏應該知道爲什麼返回 true 了。
網上還有一枚有趣的例子:
String s1 = new StringBuilder("計算機").append("軟件").toString();
System.out.println(s1.intern() == s1);
String s2 = new StringBuilder("Java(TM) SE ").append("Runtime Environment").toString();
System.out.println(s2.intern() == s2);
打印結果
true
false
可以自己研究一下爲什麼,哈哈!
PS:
圖中始終強調了 JDK 1.8,因爲在 JDK 1.6 及以下跟 1.8 的字符串常量池的存儲機制與存儲位置是不一樣的,所以結果也不一定一致。
【Java面試題與答案】整理推薦