可变的字符序列,实现可修改的字符串。StringBuffer 与 StringBuilder 的父类
属性及其构造方法
/**
* The value is used for character storage.
*/
char[] value;
/**
* The count is the number of characters used.
*/
int count;
/**
* 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];
}
value作为数组存储相关字符,count记录当前使用的字符数。
空构造方法 与 初始容量构造方法
常用方法
最主要的方法 追加字符
append方法.png
根据参数类型不同,封装的不同的追加字符串方法。最终调用的实现方法不同。
追加调用(普通字符,可变字符序列)
//与其他相比只是参数不同
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
ensureCapacityInternal()为扩充字符长度的方法 在StringBuilder 与 StringBuffer 中动态扩容最终调用的仍为此方法。
方法会判断传入容量大于0,然后与当前数组容量比对,当容量正常将触发Arrays的拷贝方法copyOf() 创建一个新的容量数组. 计算新数组的容量大小,新容量取原容量的2倍加2和入参minCapacity中较大者。然后再进行一些范围校验。新容量必需在int所支持的范围内,之所以有<=0判断是因为,在执行 (value.length << 1) + 2操作后,可能会出现int溢出的情况。如果溢出或是大于所支持的最大容量(MAX_ARRAY_SIZE为int所支持的最大值减8),则进行hugeCapacity计算,否则取newCapacity
hugeCapacity() 初始话容量范围为 Integer.MAX_VALUE - 8 ~ Integer.MAX_VALUE
https://www.jianshu.com/p/77e82f324144
private int newCapacity(int minCapacity) {
// overflow-conscious code
int newCapacity = (value.length << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > MAX_ARRAY_SIZE)
? minCapacity : MAX_ARRAY_SIZE;
}
获取当前字符数量
public int length() {
return count;
}
获取当前容量
public int capacity() {
return value.length;
}