JDK源码解析之 Java.lang.AbstractStringBuilder
這個(gè)抽象類是StringBuilder和StringBuffer的直接父類,而且定義了很多方法,因此在學(xué)習(xí)這兩個(gè)類之間建議先學(xué)習(xí) AbstractStringBuilder抽象類
該類在源碼中注釋是以JDK1.5開始作為前兩個(gè)類的父類存在的,可是直到JDK1.8的API中,關(guān)于StringBuilder和StringBuffer的父類還是Object
一、類定義
abstract class AbstractStringBuilder implements Appendable, CharSequence {}類名用abstract修飾說明是一個(gè)抽象類,只能被繼承,不能直接創(chuàng)建對(duì)象。但是它就一個(gè)抽象方法,toString方法。
實(shí)現(xiàn)了兩個(gè)接口:
-
CharSequence:這個(gè)字符序列的接口已經(jīng)很熟悉了,用來表示一個(gè)有序字符的集合
-
ApAppendable接口能夠被追加 char 序列和值的對(duì)象。如果某個(gè)類的實(shí)例打算接收來自 Formatter 的格式化輸出,那么該類必須實(shí)現(xiàn) Appendable 接口。
二、成員變量
/*** The value is used for character storage.*/ char[] value;/*** The count is the number of characters used.*/ int count;和String中的變量不同,內(nèi)部的char[] value,不再是final的了,也就意味著可變
三、構(gòu)造方法
/** * 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提供兩個(gè)構(gòu)造方法,一個(gè)是無參構(gòu)造方法。一個(gè)是傳一個(gè)capacity(代表數(shù)組容量)的構(gòu)造,這個(gè)構(gòu)造方法用于指定類中value數(shù)組的初始大小,數(shù)組大小后面還可動(dòng)態(tài)改變。
四、普通方法
AbstractStringBuilder中的方法可大致分為五類:對(duì)屬性的控制,對(duì)Value中char值的增刪改查。
4.1、屬性控制
主要是對(duì)Value的長(zhǎng)度與容量進(jìn)行的操作
1.length():
返回已經(jīng)存儲(chǔ)的實(shí)際長(zhǎng)度(就是count值)
public int length() {return count;}2.capacity():
capacity這個(gè)單詞是’容量’的意思,返回當(dāng)前value可以存儲(chǔ)的字符容量,即在下一次重新申請(qǐng)內(nèi)存之前能存儲(chǔ)字符序列的長(zhǎng)度。
public int capacity() {return value.length;}3.ensureCapacity(int minimumCapacity):
確保value數(shù)組的容量是否夠用,如果不夠用,調(diào)用4.expandCapacity(minimumCapacity)方法擴(kuò)容,參數(shù)為需要的容量
public void ensureCapacity(int minimumCapacity) {if (minimumCapacity > 0)ensureCapacityInternal(minimumCapacity);}4.expandCapacity(int minimumCapacity):
對(duì)數(shù)組進(jìn)行擴(kuò)容,參數(shù)為需要的容量
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);}擴(kuò)容的算法:
如果調(diào)用了該函數(shù),說明容量不夠用了,先將當(dāng)前容量+1的二倍(newCapacity)與需要的容量(minimumCapacity)比較。
如果比需要的容量大,那就將容量擴(kuò)大到容量+1的二倍;如果比需要的容量小,那就直接擴(kuò)大到需要的容量。
使用Arrays.copyOf()這個(gè)非常熟悉的方法來使數(shù)組容量動(dòng)態(tài)擴(kuò)大
5.trimToSize():
如果value數(shù)組的容量有多余的,那么就把多余的全部都釋放掉
public void trimToSize() {if (count < value.length) {value = Arrays.copyOf(value, count);}}6.setLength(int newLength):
強(qiáng)制增大實(shí)際長(zhǎng)度count的大小,如果 newLength 參數(shù)小于當(dāng)前長(zhǎng)度則長(zhǎng)度將更改為指定的長(zhǎng)度, 截?cái)?#xff0c;數(shù)據(jù)不變;如果 newLength 參數(shù)大于或等于當(dāng)前長(zhǎng)度則將追加有效的 null 字符 (’\u0000’),使長(zhǎng)度滿足 newLength 參數(shù)
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;} }4.2、獲取方法
1. 代碼點(diǎn)相關(guān)的五個(gè)方法:charAt(int) / codePointAt(int) / codePointBefore(int) / codePointCount(int, int) / offsetByCodePoints(int, int)
他們與String中的是一模一樣的,代碼也是一樣的(就有個(gè)變量名變動(dòng))
2. getChars(int srcBegin, int srcEnd, char dst[],int dstBegin):
復(fù)制、將value[]的[srcBegin, srcEnd)拷貝到dst[]數(shù)組的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);}3. 索引下標(biāo)
public int indexOf(String str) {return indexOf(str, 0);}public int indexOf(String str, int fromIndex) {return String.indexOf(value, 0, count, str, fromIndex);}int indexOf(String str)、int indexOf(String str, int fromIndex)
第一次出現(xiàn)的指定子字符串在該字符串中的索引,可以指定索引
int lastIndexOf(String str)、int lastIndexOf(String str, int fromIndex)
返回最右邊出現(xiàn)的指定子字符串在此字符串中的索引 ,也就是最后一個(gè),可以指定索引,指定索引就從索引處 反向匹配
4. substring(int start, int end)
根據(jù)索引返回子串
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);}5.String substring(int start)
substring(int start, int end)的簡(jiǎn)化方法,指定開始位置,默認(rèn)結(jié)束位置為最后
6. CharSequence subSequence(int start, int end)
為了實(shí)現(xiàn)CharSequence方法,內(nèi)部調(diào)用的substring
@Overridepublic CharSequence subSequence(int start, int end) {return substring(start, end);}4.3、更新方法
更新方法比較少,因?yàn)槭菙?shù)組,數(shù)組的訪問按照下標(biāo)進(jìn)行設(shè)置就好了,還提供了替換的功能,也算是更新操作
setCharAt(int index, char ch)
2.AbstractStringBuilder replace(int start, int end, String str)
使用str替換對(duì)象中從start 開始到end結(jié)束的這一段
4.4、刪除方法
1.AbstractStringBuilder delete(int start, int end)
刪除指定范圍的char
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;}2.AbstractStringBuilder deleteCharAt(int index)
刪除某個(gè)位置的char
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;}4.5、添加方法
添加元素,分為尾部追加元素和中間插入元素,由于append與insert都為一系列方法,下列系列中的一部分方法
1.append(Object obj)
利用Object(或任何對(duì)象)的toString方法轉(zhuǎn)成字符串然后添加到該value[]中
public AbstractStringBuilder append(Object obj) {return append(String.valueOf(obj));}2.append()的核心代碼:append(String str)/append(StringBuffer sb)/append(CharSequence s)
直接修改value[],并且’添加’的意思為鏈接到原value[]的實(shí)際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 differencepublic 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 differencepublic 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());}3.insert(int index, char str[], int offset,int len):(insert的核心代碼)
在value[]的下標(biāo)為index位置插入數(shù)組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;}4.6、其他方法
1. reverse()
按照字符進(jìn)行翻轉(zhuǎn)
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;}五、總結(jié)
AbstractStringBuilder就是 可變 字符序列的一個(gè)綱領(lǐng),
它規(guī)定了可變字符序列應(yīng)該有的行為,
比如 添加字符/刪除字符/更新字符/獲取字符,
因?yàn)榭勺?#xff0c;所以對(duì)于可變的支持,自然是必不可少的,
另外,他作為String在很多方面的一個(gè)替代,必然也是提供了String的一些功能方法,
否則與String API 變化巨大 也是毫無意義,
因?yàn)楫吘贡旧砭褪菫榱嗣枋鲎址蛄小?/p>
總結(jié)
以上是生活随笔為你收集整理的JDK源码解析之 Java.lang.AbstractStringBuilder的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDFS常用Shell命令
- 下一篇: JDK源码解析之 Java.lang.F