對於String的總結:
1、Java中的String類的定義如下:
1 public final class String
2 implements java.io.Serializable, Comparable<String>, CharSequence { ...}
可以看到,String是final的2、String類中定義了一個final的字符數組value[],用來存儲字符:
/** The value is used for character storage. */
private final char value[];
重要方法源碼查看
1 /** 2 * Compares this string to the specified object. The result is {@code 3 * true} if and only if the argument is not {@code null} and is a {@code 4 * String} object that represents the same sequence of characters as this 5 * object. 6 * 7 * @param anObject 8 * The object to compare this {@code String} against 9 * 10 * @return {@code true} if the given object represents a {@code String} 11 * equivalent to this string, {@code false} otherwise 12 * 13 * @see #compareTo(String) 14 * @see #equalsIgnoreCase(String) 15 */ 16 public boolean equals(Object anObject) { 17 if (this == anObject) { 18 return true; 19 } 20 if (anObject instanceof String) { 21 String anotherString = (String)anObject; 22 int n = value.length; 23 if (n == anotherString.value.length) { 24 char v1[] = value; 25 char v2[] = anotherString.value; 26 int i = 0; 27 while (n-- != 0) { 28 if (v1[i] != v2[i]) 29 return false; 30 i++; 31 } 32 return true; 33 } 34 } 35 return false; 36 }從源碼中可以看出:
先使用==進行判斷,這是對字節碼進行判斷,如果二者相同則返回true;
然後再判斷anObject是否是一個String的一個實例,這是繼續向下比較的條件;
如果anObject是一個String實例,則轉換爲String;
接下來比較兩個字符串的長度,如果長度相等,再將兩個字符串轉換爲char數組,對比相應位置上的元素。
只有類型、長度和元素都相等的情況下才返回true。
3.JVM對String的處理
http://www.blogjava.net/cheneyfree/archive/2008/05/12/200088.html
http://blog.csdn.net/qq396229783/article/details/19924393