java - StringBuffer的capacity()方法
PHP中文网
PHP中文网 2017-04-18 09:21:15
0
3
525

StringBuffer str=new StringBuffer();
StringBuffer str1=new StringBuffer(3);
System.out.println(str.capacity()); //16
System.out.println(str1.capacity()); //8
为什么str1.capacity的结果是8?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(3)
伊谢尔伦

You may have made a mistake, the output should be:

16
3

Look at the source code:

    // minimumCapacity是当前已经存储的字符长度+要追加的字符长度
    // value.length 是当前容量
    // 所以新容量=max(2*旧容量+2,追加后的字符长度)
    void expandCapacity(int minimumCapacity) {
        int newCapacity = value.length * 2 + 2;
        if (newCapacity - minimumCapacity < 0)
            newCapacity = minimumCapacity;
        if (newCapacity < 0) {
            if (minimumCapacity < 0) // overflow
                throw new OutOfMemoryError();
            newCapacity = Integer.MAX_VALUE;
        }
        value = Arrays.copyOf(value, newCapacity);
    }

The capacity will only be expanded when adding. During initialization, in addition to the default of 16, the number is set.

刘奇
给你看JDK 1.8中的构造方法:
StringBuffer的两个构造方法,继承自父类的构造方法AbstractStringBuilder:
public StringBuffer() {
    super(16);
}
public StringBuffer(int capacity) {
    super(capacity);
}
AbstractStringBuilder的构造方法:
AbstractStringBuilder(int capacity) {
    value = new char[capacity];
}      
左手右手慢动作

Run here to see Java online compilation and execution. Running environment: java v1.7.0_80

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template