java字符串方法intern記錄

public static void main(String[] args) {
        String s1 = new String("hello");
        String intern1 = s1.intern();
        String s2 = "hello";
        System.out.println(s1 == s2);
        String s3 = new String("hello") + new String("hello");
        String intern3 = s3.intern();
        String s4 = "hellohello";
        System.out.println(s3 == s4);
    }

返回結果:

在jdk1.6下運行的結果爲:

  false,false

在jdk1.7,1.8下運行的結果爲:

  false,true

對調 String intern3 = s3.intern();
        String s4 = "hellohello";之後

在jdk1.8下  false  false

 

 原因

    intern() 方法返回字符串對象的規範化表示形式。

    它遵循以下規則:對於任意兩個字符串 s 和 t,當且僅當 s.equals(t) 爲 true 時,s.intern() == t.intern() 才爲 true。
    我猜測,如果調用intern方法的時候常量池裏沒有這個字符串,會在常量池新建這個字符串,然後將String的指向指到常量池,這個時候在寫String s4 = "hellohello"; s4也會指向常量池,如果調用intern方法的時候常量池裏有這個字符串,應該是會更新對象的指向到這個常量池,但是不更新對象的地址。

  s1!=s2 是因爲聲明s1的時候常量池中初始化了這個字符串,在調用方法的時候,方法沒有對s1的對象做任何操作,只是返回了這個字符串.

  s3==s4是因爲 s3聲明的時候+操作會new一個Stringbuffer,然後app,Stringbuffer不會在常量池中初始化"hellohello"字符串,在調用方法的時候,會去常量池初始化這個字符串,並跟新s4的指針。

intern詳解見轉載http://www.jianshu.com/users/90ab66c248e6/latest_articles

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章