java.lang.AbsractStringBuilder源碼分析

一、AbstractStringBuilder類 

這個抽象類是StringBuilder和StringBuffer的直接父類,而且定義了很多方法,因此在學習這兩個類之間建議先學習 AbstractStringBuilder抽象類
該類在源碼中註釋是以JDK1.5開始作爲前兩個類的父類存在的,可是直到JDK1.8的API中,關於StringBuilder和StringBuffer的父類還是Object

abstract class AbstractStringBuilder implements Appendable, CharSequence 

實現了兩個接口,其中CharSequence這個字符序列的接口已經很熟悉了:

該接口規定了需要實現該字符序列的長度:length();
可以取得下標爲index的的字符:charAt(int index);
可以得到該字符序列的一個子字符序列: subSequence(int start, int end);
規定了該字符序列的String版本(重寫了父類Object的toString()):toString();
Appendable接口顧名思義,定義添加的’規則’:

append(CharSequence csq) throws IOException:如何添加一個字符序列
append(CharSequence csq, int start, int end) throws IOException:如何添加一個字符序列的一部分
append(char c) throws IOException:如何添加一個字符

二、AbstractStringBuilder屬性

    //該字符序列的具體存儲
    char value[];
    //實際存儲的數量 
    int count;
    
注意:(和String中的value和count不同,String中的這兩者都是不可變的(final修飾),並且不能對value[]直接操作;而AbstractStringBuilder的兩者都是可變的,並且也定義了getValues方法讓我們可以直接拿到value[],value實際上是個動態數組,和ArrayList的實現有很多相似的地方)

 三、AbstractStringBuilder構造方法

    /** 
     * This no-arg constructor is necessary for serialization of subclasses.
     */
     AbstractStringBuilder() {
    }

    /** 
     * Creates an AbstractStringBuilder of the specified capacity.
     */
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }

四、AbstractStringBuilder常用方法

public int length()

返回已經存儲的實際長度

    public int length() {
        return count;
    }

public int capacity() 

得到目前該value數組的實際大小

    public int capacity() {
        return value.length;
    }

public void ensureCapacity(int minimumCapacity) 

確保value數組的容量是否夠用,如果不夠用,調用expandCapacity(minimumCapacity)方法擴容,參數爲需要的容量

    public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > value.length) {
            expandCapacity(minimumCapacity);
        }
    }

void expandCapacity(int minimumCapacity)

對數組進行擴容,參數爲需要的容量 

void expandCapacity(int minimumCapacity) {
    int newCapacity = (value.length + 1) * 2;
        if (newCapacity < 0) {
            newCapacity = Integer.MAX_VALUE;
        } else if (minimumCapacity > newCapacity) {
        newCapacity = minimumCapacity;
    }
        value = Arrays.copyOf(value, newCapacity);
}

擴容的算法: 
如果調用了該函數,說明容量不夠用了,先將當前容量+1的二倍(newCapacity)與需要的容量(minimumCapacity)比較。 
如果比需要的容量大,那就將容量擴大到容量+1的二倍;如果比需要的容量小,那就直接擴大到需要的容量。 
使用Arrays.copyOf()這個非常熟悉的方法來使數組容量動態擴大

 public void trimToSize()

如果value數組的容量有多餘的,那麼就把多餘的全部都釋放掉

public void trimToSize() {
        if (count < value.length) {
            value = Arrays.copyOf(value, count);
        }
    }

public void setLength(int newLength)

強制增大實際長度count的大小,容量如果不夠就用 expandCapacity()擴大;將擴大的部分全部用’\0’(ASCII碼中的null)來初始化

 public void setLength(int newLength) {
    if (newLength < 0)
        throw new StringIndexOutOfBoundsException(newLength);
    if (newLength > value.length)
        expandCapacity(newLength);

    if (count < newLength) {
        for (; count < newLength; count++)
        value[count] = '\0';
    } else {
            count = newLength;
    }
}

charAt(int index)

 得到下標爲index的字符

public char charAt(int index) {
    if ((index < 0) || (index >= count))
        throw new StringIndexOutOfBoundsException(index);
    return value[index];
}

getChars(int srcBegin, int srcEnd, char dst[],int dstBegin)

將value[]的[srcBegin, srcEnd)拷貝到dst[]數組的desBegin開始處

public void getChars(int srcBegin, int srcEnd, char dst[],int dstBegin){
    if (srcBegin < 0)
        throw new StringIndexOutOfBoundsException(srcBegin);
    if ((srcEnd < 0) || (srcEnd > count))
        throw new StringIndexOutOfBoundsException(srcEnd);
        if (srcBegin > srcEnd)
            throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
    System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}

public String substring(int start)

得到子字符串 

public String substring(int start) {
        return substring(start, count);
    }

public String substring(int start, int end) {
    if (start < 0)
        throw new StringIndexOutOfBoundsException(start);
    if (end > count)
        throw new StringIndexOutOfBoundsException(end);
    if (start > end)
        throw new StringIndexOutOfBoundsException(end - start);
        return new String(value, start, end - start);
    }

public CharSequence subSequence

得到一個子字符序列

public CharSequence subSequence(int start, int end) {
        return substring(start, end);
    }

public AbstractStringBuilder reverse()

將value給倒序存放(注意改變的就是本value,而不是創建了一個新的AbstractStringBuilder然後value爲倒序)

public AbstractStringBuilder reverse() {
    boolean hasSurrogate = false;
    int n = count - 1;
    for (int j = (n-1) >> 1; j >= 0; --j) {
        char temp = value[j];
        char temp2 = value[n - j];
        if (!hasSurrogate) {
        hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE)
            || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE);
        }
        value[j] = temp2;
        value[n - j] = temp;
    }
    if (hasSurrogate) {
        // Reverse back all valid surrogate pairs
        for (int i = 0; i < count - 1; i++) {
        char c2 = value[i];
        if (Character.isLowSurrogate(c2)) {
            char c1 = value[i + 1];
            if (Character.isHighSurrogate(c1)) {
            value[i++] = c1;
            value[i] = c2;
            }
        }
        }
    }
    return this;
    }

 public abstract String toString();

:唯一的一個抽象方法

final char[] getValue() { return value; } 

唯一的一個final方法:,得到value數組。可以對其直接操作

public AbstractStringBuilder replace(int start, int end, String str)

用字符串str替換掉value[]數組的[start,end)部分

public AbstractStringBuilder replace(int start, int end, String str) {
        if (start < 0)
        throw new StringIndexOutOfBoundsException(start);
    if (start > count)
        throw new StringIndexOutOfBoundsException("start > length()");
    if (start > end)
        throw new StringIndexOutOfBoundsException("start > end");

    if (end > count)
        end = count;
    int len = str.length();
    int newCount = count + len - (end - start);
    if (newCount > value.length)
        expandCapacity(newCount);

        System.arraycopy(value, end, value, start + len, count - end);
        str.getChars(value, start);
        count = newCount;
        return this;
    }

添加的方法有很多,在此不過多解釋

public AbstractStringBuilder append(Object obj)

利用Object(或任何對象)的toString方法轉成字符串然後添加到該value[]中

public AbstractStringBuilder append(Object obj) {
    return append(String.valueOf(obj));
    }

 public AbstractStringBuilder delete(int start, int end)

刪掉value數組的[start,end)部分,並將end後面的數據移到start位置

public AbstractStringBuilder delete(int start, int end) {
    if (start < 0)
        throw new StringIndexOutOfBoundsException(start);
    if (end > count)
        end = count;
    if (start > end)
        throw new StringIndexOutOfBoundsException();
        int len = end - start;
        if (len > 0) {
            System.arraycopy(value, start+len, value, start, count-end);
            count -= len;
        }
        return this;
    }

public AbstractStringBuilder deleteCharAt(int index)

刪除下標爲index的數據,並將後面的數據前移一位

public AbstractStringBuilder deleteCharAt(int index) {
        if ((index < 0) || (index >= count))
        throw new StringIndexOutOfBoundsException(index);
    System.arraycopy(value, index+1, value, index, count-index-1);
    count--;
        return this;
    }

public int indexOf(String str)

從fromIndex開始,在value[]中找字符串str,若能找到,返回第一個字符串的第一個字符的下標

 public int indexOf(String str) {
    return indexOf(str, 0);
 }

 public int indexOf(String str, int fromIndex) {
        return String.indexOf(value, 0, count,
                              str.toCharArray(), 0, str.length(), fromIndex);
 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章