【JDK1.8源碼閱讀】String.class註釋及測試

前置說明:equals和==的區別
Java 語言裏的 equals方法其實是交給開發者去覆寫的,讓開發者自己去定義滿足什麼條件的兩個Object是equal的。參考:https://blog.csdn.net/lglglgl/article/details/104973047

Class String源碼(部分)


public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
	/**
	 * String底層是使用字符數組存儲的
	 */
	private final char value[];
	/**
	 * 用於緩存字符串的哈希值,默認爲0
	 */
	private int hash;

	private static final long serialVersionUID = -6849794470754667710L;

	private static final ObjectStreamField[] serialPersistentFields = new ObjectStreamField[0];

		/**
	 	*初始化新創建的{@code String}對象,使其表示一個空字符序列。注意,不需要這個構造函數的用法,因爲字符串是不可變的。
		*/
	public String() {
		this.value = "".value;//this.value = "".value,意思指長度爲零的空字符串
	}

	/**
	 * 新創建的字符串是一份複製品
	 * newly created string is a copy of the argument string. 
	 */
	public String(String original) {
		this.value = original.value;
		this.hash = original.hash;
	}
	
	public String(char value[]) {
		this.value = Arrays.copyOf(value, value.length);
	}


源碼註釋

  1. String底層是使用字符數組存儲的
  2. 所有String字符串被創建後就不可改變,因此創建後的字符串底層是共享的。
  3. String類裏面的value包括一個hash(int)private final char value[],廣義上只要兩者任一值不同,既是不同。

測試類

package test;

public class string {

	public static void main(String[] args) {
		String a = "hello";
		String b = "world";
		final String c = "hello";
		String d = "helloworld";
		String e = "hello" + "world";
		String f = "hello" + b;
		String g = c + b;
		String h = c + "world";
		String i = a + b;
		String j = a + b;
		System.out.println(d == e);//1
		System.out.println(d == f);//0
		System.out.println(d == g);//0
		System.out.println(d == h);//1
		System.out.println(d == i);//0
		System.out.println(g == h);//0
		System.out.println(i == j);//0
	}
}


測試類註解

name value 備註
args String[0] (id=16)
a “hello” (id=19) 內存開闢一塊空間,以字符數組存儲
b “world” (id=23) 內存開闢一塊空間,以字符數組存儲
c “hello” (id=19) 共享a,一個常量,代表了hello字符串。
d “helloworld” (id=24) 變量並指向常量池中的helloworld字符串
e “helloworld” (id=24) 變量由兩個常量相連接生成的一個helloworld字符串,與d在底層儲存是一致的
f “helloworld” (id=29) 變量由一個常量和一個變量連接生成的字符串,在運行時會在堆內存中開闢新的空間保存這個字符串。
g “helloworld” (id=31) 變量由一個常量c(即hello)和一個變量連接生成的字符串,在運行時同樣會在堆內存中開闢新的空間保存這個字符串。
h “helloworld” (id=24) 變量由一個常量c(可以認爲c就是“hello”這個字符串)和另一個常量world連接生成的一個常量helloworld,與d在底層儲存是一致的。
i “helloworld” (id=33) 變量由一個變量a和另一個變量b連接生成的新的字符串,在運行時會在堆內存中開闢新的空間保存這個字符串。
j “helloworld” (id=35) 變量由一個變量a和另一個變量b連接生成的新的字符串,在運行時會在堆內存中開闢新的空間保存這個字符串。

代碼注意

避免頻繁申請及浪費內存空間,建議使用 finalString限定,參考:
System.out.println(g == h);//0
System.out.println(d == h);//1


參考

https://blog.csdn.net/qq_21963133/article/details/79660085

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章