stringbuffer 中的capacity()函数

public class HelloWord{
public static void main(String[] args){

StringBuffer sb = new StringBuffer("abcdefgh");
System.out.println("the length is "+sb.length());
System.out.println("the capacity is "+sb.capacity());
sb.setLength(30);
System.out.println("set the length is 30");
System.out.println("the length is "+sb.length());
System.out.println("the capacity is "+sb.capacity());
sb.setLength(60);
System.out.println("set the length is 60");
System.out.println("the length is "+sb.length());
System.out.println("the capacity is "+sb.capacity());
sb.setLength(120);
System.out.println("set the length is 120");
System.out.println("the length is "+sb.length());
System.out.println("the capacity is "+sb.capacity());
}
}

结果是
the length is 8
the capacity is 24
set the length is 30
the length is 30
the capacity is 50
set the length is 60
the length is 60
the capacity is 102
set the length is 120
the length is 120
the capacity is 206
这是为什么呢

研究StringBuffer的源码就清楚了:

[code="java"] char value[];
public synchronized int capacity() {
return value.length;
}[/code]
所以capacity返回的字符数组value的长度,value用来保存StringBuffer实际的字符,这和String的实现是一样的。

构造:
[code="java"] public StringBuffer(String str) {
super(str.length() + 16); // 这里设置了value的长度, 8 + 16 正好是24
append(str);
}

// AbstractStringBuilder的构造
AbstractStringBuilder(int capacity) {
    value = new char[capacity];
}[/code]

setLength:
[code="java"] public synchronized void setLength(int newLength) {
super.setLength(newLength);
}

// AbstractStringBuilder的setLength方法
public void setLength(int newLength) {
if (newLength < 0)
    throw new StringIndexOutOfBoundsException(newLength);
if (newLength > value.length)
    expandCapacity(newLength);

if (count < newLength) {
    for (; count < newLength; count++)
    value[count] = '\0';
} else {
        count = newLength;
    }
}

// AbstractStringBuilder的expandCapacity方法
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]

看第一句就行了:
初始的capability是24,当你用
sb.setLength(30);
后,capability = (24+1)*2=50
接着:
capability = (50+1)*2=102
capability = (102+1)*2=206
...