[英]Understanding String Immutability in Java
在嘗試理解字符串不可變背后的原因時,我編寫了一個簡單的程序,如下所示:
/* Program to test string immutability */
public class StringImmutability
{
public static void main(String args[])
{
String s = "hello";
s.concat(" world"); // returns a new string object. So, the reference must point to this object for further processing like this: s = s.concat(" world");
System.out.println(s);
s = s.concat(" world");
System.out.println(s);
String s1 = s, s2 = s, s3 = s;
System.out.println(s1+" "+s2+" "+s3);
s = s.concat(" test");
//The references are modified
System.out.println(s1+" "+s2+" "+s3);
}
}
雖然輸出不符合預期:
hello
hello world
hello world hello world hello world
hello world hello world hello world
修改引用后,輸出必須重復三次hello world test
但輸出沒有任何變化。
它的工作完全符合預期。 讓我們一步一步看一下:
String s = "hello";
s.concat(" world");
這實際上是NOP,因為您沒有將concat
的結果分配給任何東西。 該新的String
實例將丟失給以太並收集垃圾,因為沒有任何引用。 因此,您s
保持不變。
s = s.concat(" world");
在這里s.concat(" world")
返回一個新的String
實例,並且您已將s
重新分配給它。 所以s
現在指向這個新字符串,並且您已經失去了對舊字符串(剛剛在其中hello
字符串)的引用。
String s1 = s, s2 = s, s3 = s;
在這里,您創建了三個變量,它們全部指向s
指向的同一字符串實例。
s = s.concat(" test");
這是您之前所做的重復。 concat
創建一個新字符串實例,並重新分配s
了這一點。 但是請記住, s1
, s2
和s3
仍指向s
所指向的內容,因此它們不會反映更改。
您僅使s
不再指向舊字符串,而是使其指向新字符串。 但是您的其他變量仍指向該舊字符串。
您的代碼證明了字符串的不變性。 您可以更改變量所引用的String,但不能更改String對象本身(除非通過在這里不討論的易變的反射技巧)。 上面的錯誤在您的預期輸出中,僅此而已。 例如,
s = s.concat(" test");
創建一個新的 String對象並將其分配給s
變量。 它沒有也不會改變原來的對象s
簡稱。
s
被重新分配給一個新字符串,該String
的目標String
值( s
預先分配)的末尾附加了" test"
String
。
s = s.concat(" test");
這不會影響存儲在s1
, s2
或s3
的String
值,因為concat
返回一個新的String
對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.