stringbuffer或stringbuilder中capacity()方法的计算单位

请问stringbuffer或stringbuilder中capacity()方法的计算单位,文档说按字符算,但算出来不一样

StringBuffer sb = new StringBuffer();
String str = "hahahahah~";
sb.append(str);
System.out.println(sb.capacity());

输出16

请高手详解,谢谢!

[quote]如果填充字符大于16,输出的也不准啊,里面是不是有个计算规律? [/quote]

是的,与有规律的。这个里面讲的有:

[url]http://www.iteye.com/problems/36793[/url]

这个帖子讲的不错,参考下:

[url]http://www.iteye.com/problems/36793[/url]

[b]new的时候,是16[/b]
[code="java"] public StringBuffer() {
super(16);
}[/code]

[b]append的时候,没有操作原来的16,所以容量不变[/b]
[code="java"] public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}[/code]

[code="java"]// 这是最大是16
System.out.println(sb.capacity());

// 这是你想要的10,字符的数量
System.out.println(sb.length());[/code]

[color=blue][b]
StringBuffer中Capacity与length是不一样的。

Capacity是你当前StringBuffer的容量,相当于座位数。

length是当前StringBuffer中字符数,相当于观众数。

清楚了吧,呵呵。[/b][/color]

[code="java"]
// 使用StringBuffer的默认构造函数,系统默认分配16个字符的空间
StringBuffer sb = new StringBuffer();
String str = "hahahahah~";
// 调用append方法后,就是str中的字符去填充分配好的内存空间
sb.append(str);

// 在你要填入的字符串的大小不大于原来已经分配的空间大小,则原有的空间大小不会变化,还是16
System.out.println(sb.capacity()); [/code]

扩展的方法:
[code="java"] void expandCapacity(int minimumCapacity) {
int newCapacity = (value.length + 1) * 2;
if (newCapacity < 0) {
newCapacity = Integer.MAX_VALUE;
} else if (minimumCapacity > newCapacity) {
newCapacity = minimumCapacity;
}
value = Arrays.copyOf(value, newCapacity);
}[/code]