StringBuffer str=new StringBuffer();
StringBuffer str1=new StringBuffer(3);
System.out.println(str.capacity()); //16
System.out.println(str1.capacity()); //8
为什么str1.capacity的结果是8?
伊谢尔伦2017-04-18 09:23:15
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.
怪我咯2017-04-18 09:23:15
给你看JDK 1.8中的构造方法:
StringBuffer的两个构造方法,继承自父类的构造方法AbstractStringBuilder:
public StringBuffer() {
super(16);
}
public StringBuffer(int capacity) {
super(capacity);
}
AbstractStringBuilder的构造方法:
AbstractStringBuilder(int capacity) {
value = new char[capacity];
}
ringa_lee2017-04-18 09:23:15
Run here to see Java online compilation and execution. Running environment: java v1.7.0_80