AbstractStringBuilder类
abstract class AbstractStringBuilder implements Appendable, CharSequence {}
AbstractStringBuilder是一个抽象类,也是StringBuilder和StringBuffer类的父类,这个类是这两个类的共同点的体现。该类实现了Appendable接口,它的实现类的对象能够被添加char序列和值。如果某个类的实例打算接收取自java.util.Formatter 的格式化输出,那么该类必须实现Appendable 接口。该类实现了CharSequence接口,CharSequence 是char值的一个可读序列。此接口对许多不同种类的 char 序列提供统一的只读访问。
构造方法
AbstractStringBuilder() {}
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
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) {
value = Arrays.copyOf(value,
newCapacity(minimumCapacity));
}
}
private int newCapacity(int minCapacity) {
// overflow-conscious code
// 将容量扩大到原来的2倍+2
int newCapacity = (value.length << 1) + 2;
// 如果扩大后没有达到需要的容量,将需要的容量设定为容量值
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
// 超出最大容量报异常
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
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);
}
将字符从此序列复制到目标字符数组dst。要复制的第一个字符在索引srcBegin 处;要复制的最后一个字符在索引 srcEnd-1 处。要复制的字符总数为 srcEnd - srcBegin。要复制到 dst 子数组的字符从索引dstBegin处开始。
append(String str)
public AbstractStringBuilder append(String str) {
if (str == null)
// 添加四个字符null
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
delete(int start, int end),replace(int start, int end, String str)
都是调用的System.arraycopy()方法
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);
}
直接new出一个新对象返回