這個抽象類是StringBuilder和StringBuffer的直接父類,而且定義了很多方法,因此在學習這兩個類之間建議先學習 AbstractStringBuilder抽象類
該類在源碼中注釋是以JDK1.5開始作為前兩個類的父類存在的,可是直到JDK1.8的API中,關于StringBuilder和StringBuffer的父類還是Object
一、類定義
abstract class AbstractStringBuilder implements Appendable, CharSequence {}
類名用abstract修飾說明是一個抽象類,只能被繼承,不能直接創建對象。但是它就一個抽象方法,toString方法。
實現了兩個接口:
-
CharSequence:這個字符序列的接口已經很熟悉了,用來表示一個有序字符的集合
-
ApAppendable接口能夠被追加 char 序列和值的對象。如果某個類的實例打算接收來自 Formatter 的格式化輸出,那么該類必須實現 Appendable 接口。
二、成員變量
/*** The value is used for character storage.*/
char[] value;/*** The count is the number of characters used.*/
int count;
和String中的變量不同,內部的char[] value,不再是final的了,也就意味著可變
三、構造方法
/** * 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提供兩個構造方法,一個是無參構造方法。一個是傳一個capacity(代表數組容量)的構造,這個構造方法用于指定類中value數組的初始大小,數組大小后面還可動態改變。
四、普通方法
AbstractStringBuilder中的方法可大致分為五類:對屬性的控制,對Value中char值的增刪改查。
4.1、屬性控制
主要是對Value的長度與容量進行的操作
1.length():
返回已經存儲的實際長度(就是count值)
public int length() {return count;}
2.capacity():
capacity這個單詞是’容量’的意思,返回當前value可以存儲的字符容量,即在下一次重新申請內存之前能存儲字符序列的長度。
public int capacity() {return value.length;}
3.ensureCapacity(int minimumCapacity):
確保value數組的容量是否夠用,如果不夠用,調用4.expandCapacity(minimumCapacity)方法擴容,參數為需要的容量
public void ensureCapacity(int minimumCapacity) {if (minimumCapacity > 0)ensureCapacityInternal(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的大小,如果 newLength 參數小于當前長度則長度將更改為指定的長度, 截斷,數據不變;如果 newLength 參數大于或等于當前長度則將追加有效的 null 字符 (’\u0000’),使長度滿足 newLength 參數
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. 代碼點相關的五個方法:charAt(int) / codePointAt(int) / codePointBefore(int) / codePointCount(int, int) / offsetByCodePoints(int, int)
他們與String中的是一模一樣的,代碼也是一樣的(就有個變量名變動)
2. 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);}
3. 索引下標
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)
第一次出現的指定子字符串在該字符串中的索引,可以指定索引
int lastIndexOf(String str)、int lastIndexOf(String str, int fromIndex)
返回最右邊出現的指定子字符串在此字符串中的索引 ,也就是最后一個,可以指定索引,指定索引就從索引處 反向匹配
4. substring(int start, int 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);}
5.String substring(int start)
substring(int start, int end)的簡化方法,指定開始位置,默認結束位置為最后
6. CharSequence subSequence(int start, int end)
為了實現CharSequence方法,內部調用的substring
@Overridepublic CharSequence subSequence(int start, int end) {return substring(start, end);}
4.3、更新方法
更新方法比較少,因為是數組,數組的訪問按照下標進行設置就好了,還提供了替換的功能,也算是更新操作
public void setCharAt(int index, char ch) {if ((index < 0) || (index >= count))throw new StringIndexOutOfBoundsException(index);value[index] = ch;
}
2.AbstractStringBuilder replace(int start, int end, String str)
使用str替換對象中從start 開始到end結束的這一段
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)
刪除某個位置的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(或任何對象)的toString方法轉成字符串然后添加到該value[]中
public AbstractStringBuilder append(Object obj) {return append(String.valueOf(obj));}
2.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 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[]的下標為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;}
4.6、其他方法
1. 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;}
五、總結
AbstractStringBuilder就是 可變 字符序列的一個綱領,
它規定了可變字符序列應該有的行為,
比如 添加字符/刪除字符/更新字符/獲取字符,
因為可變,所以對于可變的支持,自然是必不可少的,
另外,他作為String在很多方面的一個替代,必然也是提供了String的一些功能方法,
否則與String API 變化巨大 也是毫無意義,
因為畢竟本身就是為了描述字符序列。