jdk源码阅读-stringbuffer类

1
2
3
public final class 
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence

final类型,一旦创建不可改变.

1
2
3
public () {
super(16);
}

构造函数创建长度16的的char数组

1
2
3
4
public synchronized StringBuffer append(Object obj) {
super.append(String.valueOf(obj));
return this;
}
1
2
3
4
5
6
7
8
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
1
2
3
4
5
6
7
8
9
10
11
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);
}

StringBuffer中append方法,
1.当数组容量不足时,会通过value.length * 2 + 2算法进行扩容。
2.传入字符为Null时,会转换成字符”null”进行拼接