Java 中 intern() 方法有什麼用?


字串方法 intern() 返回字串物件的規範表示形式。字串類私下儲存一個最初為空的字串池。

對於任意兩個字串 s 和 t,如果且僅當 s.equals(t) 為 true 時,s.intern() == t.intern() 才為 true。

所有文字字串和字串值常量表達式都已作為內部項。

示例

 線上演示

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "This is TutorialsPoint";
      // returns canonical representation for the string object
      String str2 = str1.intern();
     
      // prints the string str2
      System.out.println(str2);
     
      // check if str1 and str2 are equal or not
      System.out.println("Is str1 equal to str2 ? = " + (str1 == str2));
   }
}

輸出

This is TutorialsPoint
Is str1 equal to str2 ? = true

更新時間:2019 年 7 月 30 日

232 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.