abstract class AbstractStringBuilder {
//字符容器 - 34
//['n','u','l','l','a','a','a','a','a','b','b','b','b','b','c','c','c','c','c'...]
char[] value;
//有效字符数
int count;//24
//capacity - 16
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
//str - "cccccccccc"
public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();//len - 10
ensureCapacityInternal(count + len);//14 + 10
//将str下标为0开始的数据添加到value数组count下标的位置,拷贝len长度
str.getChars(0, len, value, count);
count += len;
return this;
}
private AbstractStringBuilder appendNull() {
int c = count;//c - 0
ensureCapacityInternal(c + 4);//扩容 -> 0+4
final char[] value = this.value;
value[c++] = 'n';//value[0] = 'n';
value[c++] = 'u';//value[1] = 'u';
value[c++] = 'l';//value[2] = 'l';
value[c++] = 'l';//value[3] = 'l';
count = c;
return this;
}
//minimumCapacity - 24
private void ensureCapacityInternal(int minimumCapacity) {
// 有溢出意识的代码
//if(24 - 16 > 0)
if (minimumCapacity - value.length > 0) {
//value = Arrays.copyOf(value,34);
value = Arrays.copyOf(value,newCapacity(minimumCapacity));
}
}
//面试题:StringBuilder的扩容机制为什么是原来的2倍+2
//答:因为怕用户使用new StringBuilder(0)来创建对象,0<<1还是0,所以要加个2
//minCapacity - 24
private int newCapacity(int minCapacity) {
//扩容机制:数组原来长度的2倍+2
//int newCapacity = (16 << 1) + 2; --- 34
int newCapacity = (value.length << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
}
public final class StringBuilder extends AbstractStringBuilder {
public StringBuilder() {
super(16);
}
//capacity - 10000
public StringBuilder(int capacity) {
super(capacity);
}
//str - "abc"
public StringBuilder(String str) {
super(str.length() + 16);//3 + 16
append(str);
}
//str - "aaaaa"
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
}
//默认长度:10000
//StringBuilder sb = new StringBuilder(10000);
//默认长度:"abc".length() + 16
//StringBuilder sb = new StringBuilder("abc");
//默认长度:16
StringBuilder sb = new StringBuilder();
sb.append(null);
sb.append("aaaaa");
sb.append("bbbbb");
sb.append("cccccccccc");
System.out.println(sb.toString());
经验:看底层,找场景
- 看类的继承关系
- 看属性
- 看创建对象的过程
- 研究场景