String的intern理解與實踐

2021-09-29 23:52:35 字數 2654 閱讀 9206

之前遇到過乙個問題很值得思考

string s1 =

newstring

("hello");

string intern1 = s1.

intern()

;string s2 =

"hello"

;system.out.

println

(s1 == s2)

;// 返回的是false

string s3 =

newstring

("hello")+

newstring

("hello");

string intern = s3.

intern()

;string s4 =

"hellohello"

;system.out.

println

(s3 == s4)

;// 返回的是true

使用的是jdk 8

看了很多資料,感覺還是有點懵逼。然後自己做了個實驗來驗證一下結果:

system.out.

println

(s1 == intern1)

;// false

system.out.

println

(intern1 == s2)

;// true

從這兩個列印語句可以說明乙個問題 :

s1和intern1不是同乙個物件的引用,s1是堆中位址的引用,intern1則是字串常量池中的引用,故false

說明intern1 和 s2都是同乙個物件的引用,都是在常量池中的。

string s2 =

"hello"

;// 儲存在常量池中

這裡可以知道,通過""建立的物件都是儲存在常量池中的。所以s1 != s2

這裡還有一點就是可能要注意的是: new string(「hello」)的時候,實際上會建立乙個堆引用和乙個常量池引用,而常量池的引用通過intern方法建立和獲取。

**解讀:

// 建立了乙個堆物件以及常量池的,乙個堆中引用,乙個常量池中的引用

string s1 =

newstring

("hello");

// 獲取常量池中的引用,發現上面已經建立好了。這一行**其實要不要都無所謂

string intern1 = s1.

intern()

;// 獲取常量池的引用

string s2 =

"hello"

;// 堆位址和常量池位址不匹配

system.out.

println

(s1 == s2)

;// 返回的是false

system.out.

println

(new

string

("hello")==

newstring

("hello"))

;// false

system.out.

println

(new

string

("hello").

intern()

==new

string

("hello").

intern()

);// true

system.out.

println

(s3 == intern)

;// true

system.out.

println

(s4 == intern)

;// true

這兩個列印語句說明:

通過new string 建立的物件,在堆中的位置是不同的。

通過intern方法發現他們在常量池中的物件卻是相等的。

說明堆中的引用和常量池中的引用是一致的。

說明常量池中的引用就是指向堆的。

然後回到**解讀:

// 這裡實際產生了三個物件2個hello和1個hellohello。其中常量池會存在乙個hello,但是hellohello在常量池中是沒有的

string s3 =

newstring

("hello")+

newstring

("hello");

// 獲取常量池中的物件時發現沒有hellohello這個引用,所以需要引用堆中的s3的位址

string intern = s3.

intern()

;// 這裡建立s4的時候會去常量池中查詢hellohello的引用。發現上面已經建立好了

string s4 =

"hellohello"

;system.out.

println

(s3 == s4)

;// 返回的是true

如果還是有點懵逼,可以結合上面4個列印語句再看看。

如果你理解的更透徹,也請指導指導,歡迎**!

參考文章 :

String中intern的方法

首先檢視官方api那個的解釋 intern public stringintern 返回字串物件的規範化表示形式。乙個初始時為空的字串池,它由類 string 私有地維護。當呼叫 intern 方法時,如果池已經包含乙個等於此 string 物件的字串 該物件由 equals object 方法確定...

String中intern的方法

intern public string intern 返回字串物件的規範化表示形式。乙個初始時為空的字串池,它由類 string 私有地維護。當呼叫 intern 方法時,如果池已經包含乙個等於此 string 物件的字串 該物件由 equals object 方法確定 則返回池中的字串。否則,將...

String類的intern 方法

返回字串物件的規範化表示形式 當建立乙個string類的物件時,也同時建立了乙個初始為空的字串物件池,並由類string來維護。當呼叫乙個string物件的intern 方法時,類string會去查詢該字串物件池,是否包含乙個等於該物件的字串 方法是通過equals 來確定 如果存在,則會返回這個池...