1. 程式人生 > >String 原始碼解析,深入認識String

String 原始碼解析,深入認識String

問題

前些日子犯了一個很低階的錯誤,將集合A==B,然後將B拿過去使用,發現事情不對,集合A的元素也發生了變化。好尷尬啊,這就是對==號的理解不深導致的低階錯誤。正好上一篇寫了一個Stringutils類。那麼今天就讓我們深入她,理解她吧。

引入

public class VeryGood {



    public static void main(String[] args) {
        String a = "a"+"b"+1;
        String b = "ab1";
        System.out.println(a == b);


        String a1 = new
String("ab1"); String b1 = "ab1"; System.out.println(a1 == b1); } }

他們的執行結果是什麼呢?

正確答案是:

true
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, CharSequence介面。

Comparable介面有compareTo(String s)方法,CharSequence介面有length(),charAt(int index),subSequence(int start,int end)方法。

String屬性

String類中包含一個不可變的char陣列用來存放字串,一個int型的變數hash用來存放計算後的雜湊值。

/**
 * The <code>String</code> class represents character strings. All
 * string literals in Java programs, such as <code>"abc"</code>, are
 * implemented as instances of this class.
 * <p>
 * Strings are constant; their values cannot be changed after they
 * are created. String buffers support mutable strings.
 * /

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格式編碼,拷貝到value
public 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)方法通過正則表示式來判斷。

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相同,不保證記憶體一定相同,不保證字面值一定相同。