java學(xué)習(xí)隨筆2
String不可變的理解
查看String的源碼,可以發(fā)現(xiàn)String的class的修飾詞是fianl享言,各個(gè)變量的修飾詞也是final,表明它并不能改變(其實(shí)可以改變value的值對(duì)String進(jìn)行改變览露,但是Java中并沒有可以實(shí)現(xiàn)改變一個(gè)String的value數(shù)組的方法荧琼,所以可以理解為Strng是不可變的):
public final class String implements java.io.Serializable, Comparable, CharSequence
{
? ? /** The value is used for character storage. */
? ? private final char value[];
? ? /** The offset is the first index of the storage that is used. */
? ? private final int offset;
? ? /** The count is the number of characters in the String. */
? ? private final int count;
? ? /** Cache the hash code for the string */
? ? private int hash; // Default to 0
? ? /** use serialVersionUID from JDK 1.0.2 for interoperability */
? ? private static final long serialVersionUID = -6849794470754667710L;
? ? ........
}
一個(gè)小小的證明
下面代碼的輸出結(jié)果是“22”,沒有報(bào)錯(cuò)差牛。
String str=“11”命锄;
str=“22”;
System.out.println(str)偏化;
但是改成以下的代碼
String str=“11”脐恩;
System.out.println(str.hashCode());
str=“22”;
System.out.println(str.hashCode());
System.out.println(str)侦讨;
可以發(fā)現(xiàn)兩次輸出的hashCode是不一樣的驶冒,證明兩個(gè)str不是同一個(gè)對(duì)象。所以改變String的操作是新實(shí)例化了一個(gè)String對(duì)象搭伤,而不是改變員String的值只怎。