首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Java String.intern() 方法深度解析:字符串常量池與引用複用

     編輯:Java 綜合教學

方法簽名與契約

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

核心要點

  1. intern() 是運行期手動入池操作。
  2. JDK 7+ 常量池移至堆中,不再受永久代大小限制。
  3. 大量調用 intern() 可能導致常量池膨脹,需謹慎使用。
  4. 常見用途:字符串去重、節省記憶體、加速 == 比較(僅限池內字符串)。

JDK 源碼註釋(節錄)

* 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() 機制,有助於診斷字符串記憶體洩漏與優化大量字符串處理場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved