Java源碼分析02_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格式編碼,拷貝到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);
}


equals方法經常用得到,它用來判斷兩個對象從實際意義上是否相等,String對象判斷規則:

  1. 內存地址相同,則爲真。

  2. 如果對象類型不是String類型,則爲假。否則繼續判斷。

  3. 如果對象長度不相等,則爲假。否則繼續判斷。

  4. 從後往前,判斷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, value0value.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相同,不保證內存一定相同,不保證字面值一定相同。

 


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