在看StringBuilder之前,还是来先看下AbstractStringBuilder吧
成员变量
char[] value;
int count;
构造函数
AbstractStringBuilder() {
}
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
基本方法
length() 与 capacity()
public int length() {
return count;
}
public int capacity() {
return value.length;
}
空间处理(个人感觉,是AbstractStringBuilder的精髓
public void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > 0)
ensureCapacityInternal(minimumCapacity);
}
/**
* This implements the expansion semantics of ensureCapacity with no
* size check or synchronization.
*/
private void ensureCapacityInternal(int minimumCapacity) {
if (minimumCapacity - value.length > 0)
expandCapacity(minimumCapacity);
}
void expandCapacity(int minimumCapacity) {
int newCapacity = value.length * 2 + 2;
if (newCapacity - minimumCapacity < 0)
newCapacity = minimumCapacity;
if (newCapacity < 0) {
if (minimumCapacity < 0)
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
value = Arrays.copyOf(value, newCapacity);
}
public void trimToSize() {
if (count < value.length) {
value = Arrays.copyOf(value, count);
}
}
charAt 与 getChars
public char charAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
return value[index];
}
public void setCharAt(int index, char ch) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
value[index] = ch;
}
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin){
if (srcBegin <