Jdk1.8
abstract class AbstractStringBuilder
implements Appendable, CharSequence{}
AbstractStringBuilder 抽象类实现了Appendable, CharSequence接口
Appendable: 提供apend()方法接口定义
CharSequence:这里实现了length()、charArt()、subSequence()、toString()
构造方法:
AbstractStringBuilder() {}
/**
与String底层相同,字符串是用char[]实现
简单粗暴直接new一个char数组
*/
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
类成员:
//存储字符串
char[] value;
//字符串数组使用的长度
int count;
//字符串允许最大长度,也就是int类型的最大值-8,为了防止出现OutOfMemory的情况
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
类方法:
最常用的append方法
/**
添加字符串到原数据末尾
返回原对象
*/
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
//再原来基础上扩容
ensureCapacityInternal(count + len);
//将内容加入value
str.getChars(0, len, value, count);
count += len;//更新长度
return this;//返回本对象,这里不创建新对象,节约性能
}
/**
这个append null值方法真的是加了个null ^O^
*/
private AbstractStringBuilder appendNull() {
int c = count;
ensureCapacityInternal(c + 4);
final char[] value = this.value;
value[c++] = 'n';
value[c++] = 'u';
value[c++] = 'l';
value[c++] = 'l';
count = c;
return this;
}
其他方法:
//字符串扩容,返回一个不小于minCapacity的新容量值
private int newCapacity(int minCapacity) {
//扩容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;
}
//返回一个不超过Integer.MAX_VALUE的大小范围
//MAX_ARRAY_SIZE 为 MAX_VALUE-8
private int hugeCapacity(int minCapacity) {
if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > MAX_ARRAY_SIZE)
? minCapacity : MAX_ARRAY_SIZE;
}
/**
改变字符串数组长度
直接复制原本数据放入新数组,多余部分使用结束符'/0'填充
返回新的被使用的长度
*/
public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
ensureCapacityInternal(newLength);
if (count < newLength) {
//调用Arrays.fill进行copy
Arrays.fill(value, count, newLength, '\0');
}
count = newLength;
}