JDK1.8源碼學習--003、java.lang.AbstractStringBuilder

一、概述

StringBuffer 和 StringBuilder 兩者都繼承了AbstractStringBuilder、AbstractStringBuilder和String一樣,
在其內部都是以字符數組的形式實現的。也就是String,StringBuffer以及StringBuilder在其內部都是以字符數組的形式實現的。

二、類聲明

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:如何添加一個字符

三、成員屬性

 char[] value; //value爲該字符序列的具體存儲,
 int count; //count爲實際存儲的數量 

注: 

(和String中的value和count不同,String中的這兩者都是不可變的(final修飾),
並且不能對value[]直接操作;而AbstractStringBuilder的兩者都是可變的,
並且也定義了getValues方法讓我們可以直接拿到value[],value實際上是個動態數組,和ArrayList的實現有很多相似的地方)

四、構造函數

    //無參構造
    AbstractStringBuilder() {
    }

    //AbstractStringBuilder的構造函數中傳入的capacity是指容量,實際長度是以leng中的count表示
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }

五、成員方法

1.length():返回已經存儲的實際長度(就是count值)

    @Override
    public int length() {
        return count;
    }

2.capacity():這個單詞是’容量’的意思,得到目前該value數組的實際大小

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

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

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

4.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()這個非常熟悉的方法來使數組容量動態擴大

5.trimToSize():如果value數組的容量有多餘的,那麼就把多餘的全部都釋放掉

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


6.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;
        }
    }


7.charAt(int index):得到下標爲index的字符

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


8.codePointAt(int index):得到代碼點

public int codePointAt(int index) {
        if ((index < 0) || (index >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointAt(value, index);
    }


9.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);
    }


10.substring(int start)/substring(int start, int end):得到子字符串

 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);
    }


11.subSequence(int start, int end):得到一個子字符序列

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


12.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;
    }


toString():唯一的一個抽象方法:toString()

    public abstract String toString();



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

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



CRUD操作:
改:
13.setCharAt(int index, char ch):直接設置下標爲index的字符爲ch

 public void setCharAt(int index, char ch) {
    if ((index < 0) || (index >= count))
        throw new StringIndexOutOfBoundsException(index);
    value[index] = ch;
    }



14.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;
    }



增(AbstractStringBuilder類及其子類中最重要的操作;Appendable接口的具體實現)
其中append都表示’追加’,insert都表示’插入’:

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

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


16.append()的核心代碼:append(String str)/append(StringBuffer sb)/append(CharSequence s)。直接修改value[],並且’添加’的意思爲鏈接到原value[]的實際count的後面 

 public AbstractStringBuilder append(String str) {
    if (str == null) str = "null";
        int len = str.length();
    if (len == 0) return this;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    str.getChars(0, len, value, count);
    count = newCount;
    return this;
    }

    // Documentation in subclasses because of synchro difference
    public AbstractStringBuilder append(StringBuffer sb) {
    if (sb == null)
            return append("null");
    int len = sb.length();
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    sb.getChars(0, len, value, count);
    count = newCount;
    return this;
    }

    // Documentation in subclasses because of synchro difference
    public AbstractStringBuilder append(CharSequence s) {
        if (s == null)
            s = "null";
        if (s instanceof String)
            return this.append((String)s);
        if (s instanceof StringBuffer)
            return this.append((StringBuffer)s);
        return this.append(s, 0, s.length());
    }


同時注意返回的都是AbstractStringBuilder,意味着append方法可以連續無限調用,即AbstractStringBuilder對象.append(參數1).append(參數2).append(參數三)…………;

 

17.append(CharSequence s, int start, int end):添加字符序列s的部分序列,範圍是[start,end)

 public AbstractStringBuilder append(CharSequence s, int start, int end) {
        if (s == null)
            s = "null";
    if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
        throw new IndexOutOfBoundsException(
                "start " + start + ", end " + end + ", s.length() " 
                + s.length());
    int len = end - start;
    if (len == 0)
            return this;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
        for (int i=start; i<end; i++)
            value[count++] = s.charAt(i);
        count = newCount;
    return this;
    }



18.append(char str[]):添加一個字符數組

public AbstractStringBuilder append(char str[]) { 
    int newCount = count + str.length;
    if (newCount > value.length)
        expandCapacity(newCount);
        System.arraycopy(str, 0, value, count, str.length);
        count = newCount;
        return this;
    }



19.append(char str[], int offset, int len):添加一個字符數組的一部分,該部分的範圍是[offset,offset+len);

public AbstractStringBuilder append(char str[], int offset, int len) {
        int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(str, offset, value, count, len);
    count = newCount;
    return this;
    }



20.append(boolean b):添加布爾值。

public AbstractStringBuilder append(boolean b) {
        if (b) {
            int newCount = count + 4;
            if (newCount > value.length)
                expandCapacity(newCount);
            value[count++] = 't';
            value[count++] = 'r';
            value[count++] = 'u';
            value[count++] = 'e';
        } else {
            int newCount = count + 5;
            if (newCount > value.length)
                expandCapacity(newCount);
            value[count++] = 'f';
            value[count++] = 'a';
            value[count++] = 'l';
            value[count++] = 's';
            value[count++] = 'e';
        }
    return this;
    }


21.append(char c):添加一個字符

public AbstractStringBuilder append(char c) {
        int newCount = count + 1;
    if (newCount > value.length)
        expandCapacity(newCount);
    value[count++] = c;
    return this;
    }


22.append(int i):添加一個整數

public AbstractStringBuilder append(int i) {
        if (i == Integer.MIN_VALUE) {
            append("-2147483648");
            return this;
        }
        int appendedLength = (i < 0) ? stringSizeOfInt(-i) + 1 
                                     : stringSizeOfInt(i);          //stringSizeOfInt方法在下面,得到參數整數的位數。
        int spaceNeeded = count + appendedLength;
        if (spaceNeeded > value.length)
            expandCapacity(spaceNeeded);
    Integer.getChars(i, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }

 final static int [] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999,
                                     99999999, 999999999, Integer.MAX_VALUE };


    static int stringSizeOfInt(int x) {
        for (int i=0; ; i++)
            if (x <= sizeTable[i])
                return i+1;
    }


23.append(long l):添加一個長整型的數據,原理同上一個append

public AbstractStringBuilder append(long l) {
        if (l == Long.MIN_VALUE) {
            append("-9223372036854775808");
            return this;
        }
        int appendedLength = (l < 0) ? stringSizeOfLong(-l) + 1 
                                     : stringSizeOfLong(l);
        int spaceNeeded = count + appendedLength;
        if (spaceNeeded > value.length)
            expandCapacity(spaceNeeded);
    Long.getChars(l, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }

    // Requires positive x
    static int stringSizeOfLong(long x) {
        long p = 10;
        for (int i=1; i<19; i++) {
            if (x < p)
                return i;
            p = 10*p;
        }
        return 19;
    }


24.append(float f)/append(double d):添加一個浮點數。

 public AbstractStringBuilder append(float f) {
    new FloatingDecimal(f).appendTo(this);
    return this;
    }

 public AbstractStringBuilder append(double d) {
    new FloatingDecimal(d).appendTo(this);
    return this;
    }

以上是append 

 

 

以下是insert
25.insert(int index, char str[], int offset,int len):(insert的核心代碼)在value[]的下標爲index位置插入數組str的一部分,該部分的範圍爲:[offset,offset+len); 

 public AbstractStringBuilder insert(int index, char str[], int offset,
                                        int len)
    {
        if ((index < 0) || (index > length()))
        throw new StringIndexOutOfBoundsException(index);
        if ((offset < 0) || (len < 0) || (offset > str.length - len))
            throw new StringIndexOutOfBoundsException(
                "offset " + offset + ", len " + len + ", str.length " 
                + str.length);
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, index, value, index + len, count - index);
    System.arraycopy(str, offset, value, index, len);
    count = newCount;
    return this;
    }



26.insert(int offset, Object obj):在value[]的offset位置插入Object(或者說所有對象)的String版。

public AbstractStringBuilder insert(int offset, Object obj) {
    return insert(offset, String.valueOf(obj));
    }



27.insert(int offset, String str):在value[]的offset位置插入字符串

public AbstractStringBuilder insert(int offset, String str) {
    if ((offset < 0) || (offset > length()))
        throw new StringIndexOutOfBoundsException(offset);
    if (str == null)
        str = "null";
    int len = str.length();
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, offset, value, offset + len, count - offset);
    str.getChars(value, offset);
    count = newCount;
    return this;
    }



28.insert(int offset, char str[]):在value[]的offset位置插入字符數組

public AbstractStringBuilder insert(int offset, char str[]) {
    if ((offset < 0) || (offset > length()))
        throw new StringIndexOutOfBoundsException(offset);
    int len = str.length;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, offset, value, offset + len, count - offset);
    System.arraycopy(str, 0, value, offset, len);
    count = newCount;
    return this;
    }


29.insert(int dstOffset, CharSequence s)/insert(int dstOffset, CharSequence s,int start, int end):插入字符序列

public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
        if (s == null)
            s = "null";
        if (s instanceof String)
            return this.insert(dstOffset, (String)s);
        return this.insert(dstOffset, s, 0, s.length());
    }

public AbstractStringBuilder insert(int dstOffset, CharSequence s,
                                           int start, int end) {
        if (s == null)
            s = "null";
    if ((dstOffset < 0) || (dstOffset > this.length()))
        throw new IndexOutOfBoundsException("dstOffset "+dstOffset);
    if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
            throw new IndexOutOfBoundsException(
                "start " + start + ", end " + end + ", s.length() " 
                + s.length());
    int len = end - start;
        if (len == 0)
            return this;
    int newCount = count + len;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, dstOffset, value, dstOffset + len,
                         count - dstOffset);
    for (int i=start; i<end; i++)
            value[dstOffset++] = s.charAt(i);
    count = newCount;
        return this;
    }


30.插入基本類型:除了char是直接插入外,其他都是先轉成String,然後調用編號爲28的insert方法 

public AbstractStringBuilder insert(int offset, boolean b) {
    return insert(offset, String.valueOf(b));
    }


    public AbstractStringBuilder insert(int offset, char c) {
    int newCount = count + 1;
    if (newCount > value.length)
        expandCapacity(newCount);
    System.arraycopy(value, offset, value, offset + 1, count - offset);
    value[offset] = c;
    count = newCount;
    return this;
    }


    public AbstractStringBuilder insert(int offset, int i) {
    return insert(offset, String.valueOf(i));
    }


    public AbstractStringBuilder insert(int offset, long l) {
    return insert(offset, String.valueOf(l));
    }


    public AbstractStringBuilder insert(int offset, float f) {
    return insert(offset, String.valueOf(f));
    }


    public AbstractStringBuilder insert(int offset, double d) {
    return insert(offset, String.valueOf(d));
    }



刪:
31.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;
    }



32.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;
    }



查(其實CRUD前面那幾個方法中有一兩個也算查找):
33.indexOf(String str):在value[]中找字符串str,若能找到,返回第一個字符串的第一個字符的下標

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


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

public int indexOf(String str, int fromIndex) {
        return String.indexOf(value, 0, count,str.toCharArray(), 0, str.length(),fromIndex);
    }

35.lastIndexOf(String str):從後往前找

  public int lastIndexOf(String str) {
        return lastIndexOf(str, count);
    }

36.lastIndexOf(String str, int fromIndex):從後往前到fromIndex,找子串str

 public int lastIndexOf(String str, int fromIndex) {
        return String.lastIndexOf(value, 0, count,
                              str.toCharArray(), 0, str.length(), fromIndex);
    }

公衆號  關注一波  (一葉知秋博客)

          不定期分享視頻資料

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