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


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

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

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

示例

即時演示

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

更新時間:30-07-2019

230 次瀏覽

開啟你的職業生涯

完成課程獲取認證

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