標籤:
引言
從一段代碼說起:
public void stringTest(){ String a = "a"+"b"+1; String b = "ab1"; System.out.println(a == b);}
大家猜一猜結果如何?如果你的結論是true。好吧,再來一段代碼:
public void stringTest(){ String a = new String("ab1"); String b = "ab1"; System.out.println(a == b);}
結果如何呢?正確答案是false。
讓我們看看經過編譯器編譯後的代碼如何
//第一段代碼public void stringTest() { String a = "ab1"; String b = "ab1"; System.out.println(a == b);}//第二段代碼public void stringTest() { String a1 = new String("ab1"); String b = "ab1"; System.out.println(a1 == b);}
也就是說第一段代碼經過了編譯期最佳化,原因是編譯器發現"a"+"b"+1和"ab1"的效果是一樣的,都是不可變數組成。但是為什麼他們的記憶體位址會相同呢?如果你對此還有興趣,那就一起看看String類的一些重要源碼吧。
一 String類
String類被final所修飾,也就是說String對象是不可變數,並發程式最喜歡不可變數了。String類實現了Serializable, Comparable<String>, CharSequence介面。
Comparable介面有compareTo(String s)方法,CharSequence介面有length(),charAt(int index),subSequence(int start,int end)方法。
二 String屬性
String類中包含一個不可變的char數組用來存放字串,一個int型的變數hash用來存放計算後的雜湊值。
/** The value is used for character storage. */private final char value[];/** 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;
三 String建構函式
//不含參數的建構函式,一般沒什麼用,因為value是不可變數public String() { this.value = new char[0];}//參數為String類型public String(String original) { this.value = original.value; this.hash = original.hash;}//參數為char數組,使用java.utils包中的Arrays類複製public String(char value[]) { this.value = Arrays.copyOf(value, value.length);}//從bytes數組中的offset位置開始,將長度為length的位元組,以charsetName格式編碼,拷貝到valuepublic String(byte bytes[], int offset, int length, String charsetName) throws UnsupportedEncodingException { if (charsetName == null) throw new NullPointerException("charsetName"); checkBounds(bytes, offset, length); this.value = StringCoding.decode(charsetName, bytes, offset, length);}//調用public String(byte bytes[], int offset, int length, String charsetName)建構函式public String(byte bytes[], String charsetName) throws UnsupportedEncodingException { this(bytes, 0, bytes.length, charsetName);}
三 String常用方法boolean equals(Object anObject)
public boolean equals(Object anObject) { //如果引用的是同一個對象,返回真 if (this == anObject) { return true; } //如果不是String類型的資料,返回假 if (anObject instanceof String) { String anotherString = (String) anObject; int n = value.length; //如果char數組長度不相等,返回假 if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; //從後往前單個字元判斷,如果有不相等,返回假 while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } //每個字元都相等,返回真 return true; } } return false;}
equals方法經常用得到,它用來判斷兩個對象從實際意義上是否相等,String對象判斷規則:
-
記憶體位址相同,則為真。
-
如果物件類型不是String類型,則為假。否則繼續判斷。
-
如果對象長度不相等,則為假。否則繼續判斷。
-
從後往前,判斷String類中char數組value的單個字元是否相等,有不相等則為假。如果一直相等直到第一個數,則返回真。
由此可以看出,如果對兩個超長的字串進行比較還是非常費時間的。
int compareTo(String anotherString)
public int compareTo(String anotherString) { //自身對象字串長度len1 int len1 = value.length; //被比較對象字串長度len2 int len2 = anotherString.value.length; //取兩個字串長度的最小值lim int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value; int k = 0; //從value的第一個字元開始到最小長度lim處為止,如果字元不相等,返回自身(對象不相等處字元-被比較對象不相等字元) while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } //如果前面都相等,則返回(自身長度-被比較對象長度) return len1 - len2;}
這個方法寫的很巧妙,先從0開始判斷字元大小。如果兩個對象能比較字元的地方比較完了還相等,就直接返回自身長度減被比較對象長度,如果兩個字串長度相等,則返回的是0,巧妙地判斷了三種情況。
int hashCode()
public int hashCode() { int h = hash; //如果hash沒有被計算過,並且字串不為空白,則進行hashCode計算 if (h == 0 && value.length > 0) { char val[] = value; //計算過程 //s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } //hash賦值 hash = h; } return h;}
String類重寫了hashCode方法,Object中的hashCode方法是一個Native調用。String類的hash採用多項式計算得來,我們完全可以通過不相同的字串得出同樣的hash,所以兩個String對象的hashCode相同,並不代表兩個String是一樣的。
boolean startsWith(String prefix,int toffset)
public boolean startsWith(String prefix, int toffset) { char ta[] = value; int to = toffset; char pa[] = prefix.value; int po = 0; int pc = prefix.value.length; // Note: toffset might be near -1>>>1. //如果起始地址小於0或者(起始地址+所比較對象長度)大於自身對象長度,返回假 if ((toffset < 0) || (toffset > value.length - pc)) { return false; } //從所比較對象的末尾開始比較 while (--pc >= 0) { if (ta[to++] != pa[po++]) { return false; } } return true;}public boolean startsWith(String prefix) { return startsWith(prefix, 0);}public boolean endsWith(String suffix) { return startsWith(suffix, value.length - suffix.value.length);}
起始比較和末尾比較都是比較經常用得到的方法,例如在判斷一個字串是不是http協議的,或者初步判斷一個檔案是不是mp3檔案,都可以採用這個方法進行比較。
String concat(String str)
public String concat(String str) { int otherLen = str.length(); //如果被添加的字串為空白,返回對象本身 if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true);}
concat方法也是經常用的方法之一,它先判斷被添加字串是否為空白來決定要不要建立新的對象。
String replace(char oldChar,char newChar)
public String replace(char oldChar, char newChar) { //新舊值先對比 if (oldChar != newChar) { int len = value.length; int i = -1; char[] val = value; /* avoid getfield opcode */ //找到舊值最開始出現的位置 while (++i < len) { if (val[i] == oldChar) { break; } } //從那個位置開始,直到末尾,用新值代替出現的舊值 if (i < len) { char buf[] = new char[len]; for (int j = 0; j < i; j++) { buf[j] = val[j]; } while (i < len) { char c = val[i]; buf[i] = (c == oldChar) ? newChar : c; i++; } return new String(buf, true); } } return this;}
這個方法也有討巧的地方,例如最開始先找出舊值出現的位置,這樣節省了一部分對比的時間。replace(String oldStr,String newStr)方法通過Regex來判斷。
String trim()
public String trim() { int len = value.length; int st = 0; char[] val = value; /* avoid getfield opcode */ //找到字串前段沒有空格的位置 while ((st < len) && (val[st] <= ‘ ‘)) { st++; } //找到字串末尾沒有空格的位置 while ((st < len) && (val[len - 1] <= ‘ ‘)) { len--; } //如果前後都沒有出現空格,返回字串本身 return ((st > 0) || (len < value.length)) ? substring(st, len) : this;}
trim方法用起來也6的飛起
String intern()
public native String intern();
intern方法是Native調用,它的作用是在方法區中的常量池裡通過equals方法尋找等值的對象,如果沒有找到則在常量池中開闢一片空間存放字串並返回該對應String的引用,否則直接返回常量池中已存在String對象的引用。
將引言中第二段代碼
//String a = new String("ab1");//改為String a = new String("ab1").intern();
則結果為為真,原因在於a所指向的地址來自於常量池,而b所指向的字串常量預設會調用這個方法,所以a和b都指向了同一個地址空間。
int hash32()
private transient int hash32 = 0;int hash32() { int h = hash32; if (0 == h) { // harmless data race on hash32 here. h = sun.misc.Hashing.murmur3_32(HASHING_SEED, value, 0, value.length); // ensure result is not zero to avoid recalcing h = (0 != h) ? h : 1; hash32 = h; } return h;}
在JDK1.7中,Hash相關集合類在String類作key的情況下,不再使用hashCode方式離散資料,而是採用hash32方法。這個方法預設使用系統目前時間,String類地址,System類地址等作為因子計算得到hash種子,通過hash種子在經過hash得到32位的int型數值。
public int length() { return value.length;}public String toString() { return this;}public boolean isEmpty() { return value.length == 0;}public char charAt(int index) { if ((index < 0) || (index >= value.length)) { throw new StringIndexOutOfBoundsException(index); } return value[index];}
以上是一些簡單的常用方法。
總結
String對象是不可變類型,傳回型別為String的String方法每次返回的都是新的String對象,除了某些方法的某些特定條件返回自身。
String對象的三種比較方式:
==記憶體比較:直接對比兩個引用所指向的記憶體值,精確簡潔直接明了。
equals字串值比較:比較兩個引用所指對象字面值是否相等。
hashCode字串數值化比較:將字串數值化。兩個引用的hashCode相同,不保證記憶體一定相同,不保證字面值一定相同。
Java String 源碼淺析