簡體   English   中英

了解Java中的字符串不變性

[英]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了這一點。 但是請記住, s1s2s3仍指向s 指向的內容,因此它們不會反映更改。

您僅使s不再指向舊字符串,而是使其指向新字符串。 但是您的其他變量仍指向該舊字符串。

您的代碼證明了字符串的不變性。 您可以更改變量所引用的String,但不能更改String對象本身(除非通過在這里不討論的易變的反射技巧)。 上面的錯誤在您的預期輸出中,僅此而已。 例如,

s = s.concat(" test"); 

創建一個新的 String對象並將其分配給s變量。 它沒有也不會改變原來的對象s簡稱。

s被重新分配給一個新字符串,該String的目標String值( s預先分配)的末尾附加了" test" String

s = s.concat(" test");

這不會影響存儲在s1s2s3String值,因為concat返回一個新的String對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM