一起學(xué)JDK源碼 -- AbstractStringBuilder類

查看所有目錄
前一篇查看了String類的源碼,發(fā)現(xiàn)String類中有不少地方使用了StringBuffer和StringBuilder類,而這兩個(gè)類都是繼承自AbstractStringBuilder類,里面的很多實(shí)現(xiàn)都是直接使用父類的,所以就看一下AbstractStringBuilder類的源碼。

類的申明:

abstract class AbstractStringBuilder implements Appendable, CharSequence {}

1.默認(rèn)訪問控制修飾符,說明只能在包內(nèi)使用,即只能在JDK內(nèi)部使用,可能有人會(huì)問我創(chuàng)建一個(gè)java.lang包然后里面的類就可以使用AbstractStringBuilder類了,想法不錯(cuò),但jkd不允許,會(huì)報(bào)SecurityException : Prohibited package name: java.lang。故這個(gè)類只是給StringBuffer和StringBuilder類使用的。
2.類名用abstract修飾說明是一個(gè)抽象類,只能被繼承,不能直接創(chuàng)建對(duì)象。查了里面的方法你會(huì)發(fā)現(xiàn)它就一個(gè)抽象方法,toString方法。
3.實(shí)現(xiàn)了Appendable接口,Appendable能夠被追加 char 序列和值的對(duì)象。如果某個(gè)類的實(shí)例打算接收來自 Formatter 的格式化輸出,那么該類必須實(shí)現(xiàn) Appendable 接口。
4.實(shí)現(xiàn)了Charsequence接口,代表該類,或其子類是一個(gè)字符序列。

成員變量:

    char[] value;
    int count;

value用于承裝字符序列,count數(shù)組中實(shí)際存儲(chǔ)字符的數(shù)量。這里的value同String類中的value不同,String類中的value是final的不可被修改,這里的value是動(dòng)態(tài)的,并且可提供給外部直接操作。

構(gòu)造函數(shù):

    AbstractStringBuilder() {
    }
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }

AbstractStringBuilder提供兩個(gè)構(gòu)造函數(shù),一個(gè)是無(wú)參構(gòu)造函數(shù)。一個(gè)是傳一個(gè)capacity(代表數(shù)組容量)的構(gòu)造,這個(gè)構(gòu)造函數(shù)用于指定類中value數(shù)組的初始大小,數(shù)組大小后面還可動(dòng)態(tài)改變。

其它方法:

length:

    public int length() {
        return count;
    }

返回已經(jīng)存儲(chǔ)字符序列的實(shí)際長(zhǎng)度,即count的值。

capacity:

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

返回當(dāng)前value可以存儲(chǔ)的字符容量,即在下一次重新申請(qǐng)內(nèi)存之前能存儲(chǔ)字符序列的長(zhǎng)度。新添加元素的時(shí)候,可能會(huì)對(duì)數(shù)組進(jìn)行擴(kuò)容。

ensureCapacity:

    public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > 0)
            ensureCapacityInternal(minimumCapacity);
    }    

該方法是用來確保容量至少等于指定的最小值,是該類的核心也是其兩個(gè)實(shí)現(xiàn)類StringBuffer和StringBuilder的核心。通過這種方式來實(shí)現(xiàn)數(shù)組的動(dòng)態(tài)擴(kuò)容。下面來看下其具體邏輯。
1.判斷入?yún)inimumCapacity是否有效,即是否大于0,大于0執(zhí)行ensureCapacityInternal方法,小于等于0則忽略。

    private void ensureCapacityInternal(int minimumCapacity) {
        if (minimumCapacity - value.length > 0) {
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }

2.判斷入?yún)⑷萘恐凳欠癖仍萘看螅绻笥谠萘浚瑘?zhí)行擴(kuò)容操作,實(shí)際上就是創(chuàng)建一個(gè)新容量的數(shù)組,然后再將原數(shù)組中的內(nèi)容拷貝到新數(shù)組中,如果小于或等于原容量則忽略。

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;    
    private int newCapacity(int minCapacity) {
        // overflow-conscious code
        int newCapacity = (value.length << 1) + 2;
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
            ? hugeCapacity(minCapacity)
            : newCapacity;
    }

3.計(jì)算新數(shù)組的容量大小,新容量取原容量的2倍加2和入?yún)inCapacity中較大者。然后再進(jìn)行一些范圍校驗(yàn)。新容量必需在int所支持的范圍內(nèi),之所以有<=0判斷是因?yàn)椋趫?zhí)行 (value.length << 1) + 2操作后,可能會(huì)出現(xiàn)int溢出的情況。如果溢出或是大于所支持的最大容量(MAX_ARRAY_SIZE為int所支持的最大值減8),則進(jìn)行hugeCapacity計(jì)算,否則取newCapacity

private int hugeCapacity(int minCapacity) {
        if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
            throw new OutOfMemoryError();
        }
        return (minCapacity > MAX_ARRAY_SIZE)
            ? minCapacity : MAX_ARRAY_SIZE;
    }

4.這一步先進(jìn)行范圍檢查,必須在int所支持的最大范圍內(nèi)。然后在minCapacity與MAX_ARRAY_SIZE之間取較大者,此方法取的范圍是Integer.MAX_VALUE - 8到Integer.MAX_VALUE之間的范圍。
5.總結(jié):
1.通過value = Arrays.copyOf(value,newCapacity(minimumCapacity));進(jìn)行擴(kuò)容
2.新容量取 minCapacity,原容量乘以2再加上2中較大的,但不能大于int所支持的最大范圍。
3.在實(shí)際環(huán)境中在容量遠(yuǎn)沒達(dá)到MAX_ARRAY_SIZE的時(shí)候就報(bào)OutOfMemoryError異常了,其實(shí)就是在復(fù)制的時(shí)候創(chuàng)建了數(shù)組char[] copy = new char[newLength];這里支持不了那么大的內(nèi)存消耗,可以通過 -Xms256M -Xmx768M設(shè)置最大內(nèi)存。

trimToSize:

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

減少字符序列的使用空間,比如申請(qǐng)了100字符長(zhǎng)度的空間,但是現(xiàn)在只用了60個(gè),那剩下的40個(gè)無(wú)用的空間放在那里占內(nèi)存,可以調(diào)用此方法釋放掉未用到的內(nèi)存。原理很簡(jiǎn)單,只申請(qǐng)一個(gè)count大小的數(shù)組把原數(shù)組中的內(nèi)容復(fù)制到新數(shù)組中,原來的數(shù)組由于沒有被任何引用所指向,之后會(huì)被gc回收。

setLength:

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

用空字符填充未使用的空間。首先對(duì)數(shù)組進(jìn)行擴(kuò)容,然后將剩余未使用的空間全部填充為'0'字符。

charAt:

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

獲取字符序列中指定位置的字符,范圍為0到count,超出范圍拋StringIndexOutOfBoundsException異常。

codePointAt:

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

獲取字符序列中指定位置的字符,所對(duì)應(yīng)的代碼點(diǎn),即ascii碼。

codePointBefore:

    public int codePointBefore(int index) {
        int i = index - 1;
        if ((i < 0) || (i >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointBeforeImpl(value, index, 0);
    }

獲取字符序列中指定位置的前一個(gè)位置的字符,所對(duì)應(yīng)的代碼點(diǎn)。

codePointCount:

    public int codePointCount(int beginIndex, int endIndex) {
        if (beginIndex < 0 || endIndex > count || beginIndex > endIndex) {
            throw new IndexOutOfBoundsException();
        }
        return Character.codePointCountImpl(value, beginIndex, endIndex-beginIndex);
    }

獲取字符串代碼點(diǎn)個(gè)數(shù),是實(shí)際上的字符個(gè)數(shù)。不清楚代碼點(diǎn)可查看java中代碼點(diǎn)與代碼單元的區(qū)別

    public int offsetByCodePoints(int index, int codePointOffset) {
        if (index < 0 || index > value.length) {
            throw new IndexOutOfBoundsException();
        }
        return Character.offsetByCodePointsImpl(value, 0, value.length,
                index, codePointOffset);
    }

返回此字符序列中從給定的index處偏移codePointOffset個(gè)代碼點(diǎn)的索引。不清楚代碼點(diǎn)的可以查看java中代碼點(diǎn)與代碼單元的區(qū)別

getChars:

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

將字符序列中指定區(qū)間srcBegin到srcEnd內(nèi)的字符拷貝到dst字符數(shù)組中從dstBegin開始往后的位置中。

setCharAt:

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

設(shè)置字符序列中指定索引index位置的字符為ch。

append系列:

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

AbstractStringBuilder類中有一系列append方法,作用是在原字符序列后添加給定的對(duì)象或元素所對(duì)應(yīng)的字符序列。這里挑一個(gè)代表講解,其它方法原理類似。
1.首先判斷所傳參數(shù)是否為null,如果為null則調(diào)用appendNull方法,實(shí)際上就是在原字符序列后加上"null"序列。
2如果不為null則進(jìn)行擴(kuò)容操作,最小值為count+len,這一步可能增加容量也可能不增加,當(dāng)count+len小于或等于capacity就不用進(jìn)行擴(kuò)容。
3.然后再將參數(shù)的字符串序列添加到value中。
4.最后返回this,注意這里返回的是this,也就意味者,可以在一條語(yǔ)句中多次調(diào)用append方法,即大家所知的方法調(diào)用鏈。原理簡(jiǎn)單,但思想值得借鑒。asb.append("hello").append("world");

appendCodePoint:

    public AbstractStringBuilder appendCodePoint(int codePoint) {
        final int count = this.count;

        if (Character.isBmpCodePoint(codePoint)) {
            ensureCapacityInternal(count + 1);
            value[count] = (char) codePoint;
            this.count = count + 1;
        } else if (Character.isValidCodePoint(codePoint)) {
            ensureCapacityInternal(count + 2);
            Character.toSurrogates(codePoint, value, count);
            this.count = count + 2;
        } else {
            throw new IllegalArgumentException();
        }
        return this;
    }

添加代碼點(diǎn),將入?yún)⑥D(zhuǎn)換為對(duì)應(yīng)的代碼點(diǎn)后,添加到原字符序列結(jié)尾。不清楚代碼點(diǎn)的可以查看java中代碼點(diǎn)與代碼單元的區(qū)別

delete:

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

刪除字符序列指定區(qū)間的內(nèi)容。這個(gè)操作不改變?cè)蛄械娜萘俊?/p>

deleteCharAt:

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

刪除字符序列中指定索引index位置的字符。

replace:

    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);
        ensureCapacityInternal(newCount);
        System.arraycopy(value, end, value, start + len, count - end);
        str.getChars(value, start);
        count = newCount;
        return this;
    }

將原字符序列指定區(qū)間start到end區(qū)間內(nèi)的內(nèi)容替換為str,替換過程中序列長(zhǎng)度會(huì)改變,所以需要進(jìn)行擴(kuò)容和改就count的操作。

substring:

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

切割原字符序列指定區(qū)間start到end內(nèi)的內(nèi)容,返回字符串形式。

insert系列:

    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();
        ensureCapacityInternal(count + len);
        System.arraycopy(value, offset, value, offset + len, count - offset);
        str.getChars(value, offset);
        count += len;
        return this;
    }

insert系列作用是將給定定對(duì)象所對(duì)應(yīng)的字符串插入到原序列的指定位置。insert系列同append系列類似,只不過append是在原序列末尾添加元素,insert是在指定位置插入元素。這里也選一個(gè)代表進(jìn)行講解。
假設(shè)原字符序列為"hello"現(xiàn)調(diào)用insert(int 1, “aa");
1.對(duì)待插入的位置offset進(jìn)行檢查,必須在容量?jī)?nèi)
2.如果傳入對(duì)象為null則插入"null"字符串
3.對(duì)value數(shù)組進(jìn)行擴(kuò)容
4.通過System.arraycopy對(duì)數(shù)組進(jìn)行復(fù)制
arraycopy(Object src,int srcPos,Object dest,int destPos,int length);
src:源數(shù)組; ['h','e','l','l','o','o']
srcPos:源數(shù)組要復(fù)制的起始位置;1
dest:目的數(shù)組; ['h','e','l','l','o','w']
destPos:目的數(shù)組放置的起始位置; 1+2=3
length:復(fù)制的長(zhǎng)度。 6-1=5
則執(zhí)行完這句后value中的內(nèi)容為['h','e','l','e','l','l','o','o']
可以看到是將位置1到結(jié)尾的內(nèi)容后移了兩個(gè)長(zhǎng)度,因?yàn)樾枰迦氲淖址?bb"的長(zhǎng)度為2
5.將str的內(nèi)容復(fù)制到value中
str.getChars(value, offset);//將str的內(nèi)容復(fù)制到value中從offset 1位置開始復(fù)制
復(fù)制完成后['h','b','b','e','l','l','o','o'],即我們最終想要達(dá)到的效果"hbbellow"

indexOf:

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

查詢給定字符串在原字符序列中第一次出現(xiàn)的位置。調(diào)用的其實(shí)是String類的indexOf方法,具體可查看一起學(xué)JDK源碼 -- String類

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

該方法用于將字符序列反轉(zhuǎn),如"hellow"執(zhí)行reverse后變成"wolleh"。
1.hasSurrogates用于判斷字符序列中是否包含surrogates pair
2.將字符反轉(zhuǎn),count為數(shù)組長(zhǎng)度,因?yàn)槭菑?開始的所以這里需要減1。具體轉(zhuǎn)換是第一個(gè)字符與最后一個(gè)字符對(duì)調(diào),第二個(gè)字符與倒數(shù)第二個(gè)字符對(duì)調(diào),依次類推
3.實(shí)際上上述操作只需要循環(huán)(n-1) /2 + 1次[判斷條件j>=0所以要+1次,源碼中>>1就是除以2]就可以了,如數(shù)組長(zhǎng)度為9則需要循環(huán) (9-1-1)/2 +1 = 4次,9個(gè)字符對(duì)調(diào)次,第5個(gè)位置的字符不用換,如果長(zhǎng)度為10需要循環(huán)(10-1-1)/2 +1 = 5次
4.剩下的工作就是兩個(gè)位置的元素互換。
5.如果序列中包含surrogates pair 則執(zhí)行reverseAllValidSurrogatePairs方法

reverseAllValidSurrogatePairs:

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

Surrogate Pair是UTF-16中用于擴(kuò)展字符而使用的編碼方式,是一種采用四個(gè)字節(jié)(兩個(gè)UTF-16編碼)來表示一個(gè)字符。
char在java中是16位的,剛好是一個(gè)UTF-16編碼。而字符串中可能含有Surrogate Pair,但他們是一個(gè)單一完整的字符,只不過是用兩個(gè)char來表示而已,因此在反轉(zhuǎn)字符串的過程中Surrogate Pairs 是不應(yīng)該被反轉(zhuǎn)的。而reverseAllValidSurrogatePairs方法就是對(duì)Surrogate Pair進(jìn)行處理。

toString:

public abstract String toString();

這是這個(gè)抽象類中唯一的一個(gè)抽象方法,需要子類去實(shí)現(xiàn)。
查看所有目錄

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 查看所有目錄String類是我們?nèi)粘i_發(fā)中使用最頻繁的類之一,曾今有人說String類用的好壞能評(píng)判你是否是一個(gè)合...
    Kinsanity閱讀 5,907評(píng)論 0 3
  • 一、基本數(shù)據(jù)類型 注釋 單行注釋:// 區(qū)域注釋:/* */ 文檔注釋:/** */ 數(shù)值 對(duì)于byte類型而言...
    龍貓小爺閱讀 4,288評(píng)論 0 16
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,868評(píng)論 18 139
  • 看別人做的挺好看的,自己試了一下,第一次,手殘黨啊,感覺臟兮兮的。 其實(shí)看實(shí)圖是很漂亮緋紅色,還有指甲油亮片也是很...
    淺淺歲月荒度余生閱讀 431評(píng)論 4 11
  • 沉迷工具安利,買了新筆,水自閑家的如一。 買了北斗齋的水彩書。 就差顏料了,不知道買什么好。 時(shí)間緊湊,挨個(gè)上圖吧...
    敬千帆閱讀 253評(píng)論 2 3