public native String intern();
規範:返回字符串對象的標準化表示形式。JVM 維護一個私有的字符串常量池(String Pool)。
equals() 相等的字符串 → 返回池中引用。等價關係:對任意字符串 s、t,s.intern() == t.intern() 當且僅當 s.equals(t) 為 true。
所有字面值("ab")與編譯期常量表達式自動進入常量池,故 "ab".intern() == "ab" 恆為 true。
public class Str2 {
public static void test() {
String a = "a";
String b = a + "b"; // 運行期拼接,新對象
String c = "ab"; // 編譯期常量,進池
String d = new String(b); // 显式新建對象
System.out.println(b == c); // false(不同對象)
System.out.println(d == c); // false
System.out.println(c == d.intern()); // true(d.intern() 返回池中 "ab")
System.out.println(b.intern() == d.intern()); // true(同池引用)
}
public static void main(String[] args) { test(); }
}
false false true true
intern() 是運行期手動入池操作。intern() 可能導致常量池膨脹,需謹慎使用。== 比較(僅限池內字符串)。* Returns a canonical representation for the string object. * A pool of strings, initially empty, is maintained privately by the class String. * When the intern method is invoked, if the pool already contains a string equal * to this String object as determined by the equals(Object) method, then the * string from the pool is returned. Otherwise, this String object is added to * the pool and a reference to this String object is returned.
理解 intern() 機制,有助於診斷字符串記憶體洩漏與優化大量字符串處理場景。