這份JDK源碼解析,建議反覆觀看,寫的真的跟詳細了!

1. 概述

這個抽象類是StringBuilder和StringBuffer的直接父類,實現了兩個接口分別是Appendable, CharSequencejava

CharSequence是一個字符序列的接口,主要提供了一下的方法c++

該接口規定了須要實現該字符序列的長度:length(); 能夠取得下標爲index的的字符:charAt(int index); 能夠獲得該字符序列的一個子字符序列: subSequence(int start, int end); 重寫了父類Object的toString():toString(); Appendable 定義添加的規則數組

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

2.類圖

3.屬性

char[] value; 記錄字符的空間 int count; char數組中 實際字符的數量app

4.構造方法

默認構造方法AbstractStringBuilder()ide

AbstractStringBuilder(int capacity)ui

根據傳入的參數初始化char數組空間this

AbstractStringBuilder(int capacity) {
	value = new char[capacity];
}
複製代碼

5.返回長度/大小

length()spa

public int length() {
		return count;
}
複製代碼

capacity()code

public int capacity() {
		return value.length;
}
複製代碼

length()返回的是char數組中實際字符的個數

capacity返回的是數組的空間大小

6.擴容

ensureCapacity(int minimumCapacity)

public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > 0)
            ensureCapacityInternal(minimumCapacity);
    }
		private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        if (minimumCapacity - value.length > 0)//傳入的參數大於如今數組的空間則擴容
            expandCapacity(minimumCapacity);
    }
		void expandCapacity(int minimumCapacity) {
        int newCapacity = value.length * 2 + 2;//新空間爲(原來空間+1)*2
        if (newCapacity - minimumCapacity < 0)//若心的空間比傳入的參數小,則新空間爲傳入的參數
            newCapacity = minimumCapacity;
        if (newCapacity < 0) {//若新空間小於0 // int越界後可能出現小於0的狀況
            if (minimumCapacity < 0) // 傳入的參數也小於0 則拋出異常
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;//將新的空間設置爲int的最大值
        }
        value = Arrays.copyOf(value, newCapacity);//拷貝數組
    }
複製代碼

setLength(int newLength)

public void setLength(int newLength) {
        if (newLength < 0)
            throw new StringIndexOutOfBoundsException(newLength);
        ensureCapacityInternal(newLength);

        if (count < newLength) {
            Arrays.fill(value, count, newLength, '\0');
        }

        count = newLength;
    }
複製代碼

這也是擴容方法,內部調用ensureCapacityInternal來實現擴容

以後將數組空的位置填充滿

7.縮容

trimToSize()

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

調用這個方法,若當前的字符的數量小於char數組空間大小 則縮容,發起拷貝數組。釋放多餘的空間

8.獲得字符

charAt(int index)

直接返回下標對應的字符,若超出範圍則拋出異常

9.獲得子字符串/子序列

substring(int start)/substring(int start, int end)/subSequence(int start,int end)

public String substring(int start) {
        return substring(start, count);
    }
		public CharSequence subSequence(int start, int end) {
        return substring(start, end);
    }
		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);
    }
複製代碼

調用String的構造方法來實現截取子串。

10.修改字符

setCharAt(int index,char ch)

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

replace(int start, int end, String str)

用字符串str替換 start到end部分的字符 前閉後開[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
            end = count;
        int len = str.length();
  			//todo 爲何要擴容
        int newCount = count + len - (end - start);
        ensureCapacityInternal(newCount);
				// 拷貝數組 替換
        System.arraycopy(value, end, value, start + len, count - end);
        str.getChars(value, start);
        count = newCount;
        return this;
    }
複製代碼

11.追加字符串

該類提供的append()有不少

public AbstractStringBuilder append(Object obj) {
        return append(String.valueOf(obj));
    }
		public AbstractStringBuilder append(String str) {
        if (str == null)//若字符串爲空
            return appendNull();//而是添加"null"進字符串數組中
        int len = str.length();
        ensureCapacityInternal(count + len);
        str.getChars(0, len, value, count);
        count += len;
        return this;
    }
		private AbstractStringBuilder appendNull() {
        int c = count;
        ensureCapacityInternal(c + 4);
        final char[] value = this.value;
        value[c++] = 'n';
        value[c++] = 'u';
        value[c++] = 'l';
        value[c++] = 'l';
        count = c;
        return this;
    }

    // Documentation in subclasses because of synchro difference
    public AbstractStringBuilder append(StringBuffer sb) {
        if (sb == null)
            return appendNull();
        int len = sb.length();
        ensureCapacityInternal(count + len);
        sb.getChars(0, len, value, count);
        count += len;
        return this;
    }
		/**
     * @since 1.8
     */
    AbstractStringBuilder append(AbstractStringBuilder asb) {
        if (asb == null)
            return appendNull();
        int len = asb.length();
        ensureCapacityInternal(count + len);
        asb.getChars(0, len, value, count);
        count += len;
        return this;
    }

    // Documentation in subclasses because of synchro difference
    @Override
    public AbstractStringBuilder append(CharSequence s) {
        if (s == null)
            return appendNull();
        if (s instanceof String)
            return this.append((String)s);
        if (s instanceof AbstractStringBuilder)
            return this.append((AbstractStringBuilder)s);

        return this.append(s, 0, s.length());
    }
		public AbstractStringBuilder append(char[] str) {
        int len = str.length;
        ensureCapacityInternal(count + len);
        System.arraycopy(str, 0, value, count, len);
        count += len;
        return this;
    }
		public AbstractStringBuilder append(boolean b) {//添加的布爾將其轉換成對應的字符的表達
        if (b) {
            ensureCapacityInternal(count + 4);
            value[count++] = 't';
            value[count++] = 'r';
            value[count++] = 'u';
            value[count++] = 'e';
        } else {
            ensureCapacityInternal(count + 5);
            value[count++] = 'f';
            value[count++] = 'a';
            value[count++] = 'l';
            value[count++] = 's';
            value[count++] = 'e';
        }
        return this;
    }
    public AbstractStringBuilder append(char c) {
        ensureCapacityInternal(count + 1);
        value[count++] = c;
        return this;
    }
		// int long float double. 不一一列舉了
		public AbstractStringBuilder append(int i) {
        if (i == Integer.MIN_VALUE) {
            append("-2147483648");
            return this;
        }
        int appendedLength = (i < 0) ? Integer.stringSize(-i) + 1
                                     : Integer.stringSize(i);
        int spaceNeeded = count + appendedLength;
        ensureCapacityInternal(spaceNeeded);
        Integer.getChars(i, spaceNeeded, value);
        count = spaceNeeded;
        return this;
    }
複製代碼

除了參數類型不一樣 其餘都差很少,執行擴容並添加操做。直接連接到原value[]的實際count的後面

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

12.插入字符串

除了能夠在末尾追加字符串 還能夠在任意的位置進行插入字符串.

在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);
        ensureCapacityInternal(count + len);
        System.arraycopy(value, index, value, index + len, count - index);
        System.arraycopy(str, offset, value, index, len);
        count += len;
        return this;
    }
複製代碼

原理也都同樣,擴容,而後在指定的位置插入,也就是拷貝數組

還有的插入方法以下:

insert(int offset,Object obj) insert(int offset, String str) insert(int offset, char str[]) insert(int dstOffset, CharSequence s)/insert(int dstOffset, CharSequence s,int start, int end):插入字符序列 插入基本類型insert(int offset, boolean b) /insert(int offset, char c)/insert(int offset, int i)/insert(int offset, float f)/insert(int offset, double d)

13.刪除

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;
    }
複製代碼

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;
    }
複製代碼

14.查找

indexOf(String str):在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, fromIndex);
    }
複製代碼

lastIndexOf(String str):從後往前找

public int lastIndexOf(String str) {
        return lastIndexOf(str, count);
    }
		public int lastIndexOf(String str, int fromIndex) {
        return String.lastIndexOf(value, 0, count, str, fromIndex);
    }
複製代碼

都是藉助了String中的查找的方法

15.翻轉字符串

reverse 將字符串首尾顛倒

public AbstractStringBuilder reverse() {
        boolean hasSurrogates = false;
        int n = count - 1;
        for (int j = (n-1) >> 1; j >= 0; j--) {
            int k = n - j;
            char cj = value[j];
            char ck = value[k];
            value[j] = ck;
            value[k] = cj;
            if (Character.isSurrogate(cj) ||
                Character.isSurrogate(ck)) {
                hasSurrogates = true;
            }
        }
        if (hasSurrogates) {
            reverseAllValidSurrogatePairs();
        }
        return this;
    }
		private void reverseAllValidSurrogatePairs() {
        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;
                }
            }
        }
    }
複製代碼

最後

感謝你看到這裏,看完有什麼的不懂的能夠在評論區問我,以爲文章對你有幫助的話記得給我點個贊,天天都會分享java相關技術文章或行業資訊,歡迎你們關注和轉發文章!

相關文章
相關標籤/搜索