String 被聲明為 final,是不可變的,它也不可被繼承。
通過源碼瞭解 String 的不可變性
在 Java 8 中,String 是使用 char 數組實現的。
public final class String implements java.io.Serializable, Comparable<string>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
}/<string>
到了 Java 9 ,String 類的實現改用 byte 數組實現,同時使用 coder 來標識使用了哪種編碼。
public final class String
implements java.io.Serializable, Comparable<string>, CharSequence { /** The value is used for character storage. */ private final byte[] value;
/** The identifier of the encoding used to encode the bytes in {@code value}. */ private final byte coder;}/<string>
我們可以看到,value 數組被聲明為 final,並且 String 內部也沒有改變 value 數組的方法,因此 String 是不可變的。
不可變的優勢
1. 線程安全
因為 String 的不可變性,所以在多線程的環境下,可以被安全使用。
2. hash 值不需要重複計算
一個 String 被創建後,那麼它的 hash 值只需要計算一次;
比如使用 String 做為 HashMap 中的 key ,那麼不需要重複計算 hash 值。
3. String Pool
一個 String 被創建後,被可以放入 String Pool 中,就可以被其他地方所引用;因為 String 是不可變的,所以才能實現 String Pool 。
String, StringBuffer, StringBuilder
1. 不可變性
- String 不可變
- StringBuffer 和 StringBuilder 可變
2. 線程安全
- String 不可變,因此是線程安全的
- StringBuilder 不是線程安全的
- StringBuffer 是線程安全的,內部使用 synchronized 進行同步
我將持續分享Java開發、架構設計、程序員職業發展等方面的見解,希望能得到你的關注;關注我後,可私信發送數字【1】,獲取學習資料。
閱讀更多 會點代碼的大叔 的文章