public class test {
public static void main(String[] args) {
StringBuffer str = new StringBuffer();
str.append("12345");
System.out.println(str.capacity()); //16
System.out.println(str.length()); //5
str.append("67890123456");
System.out.println(str.capacity()); //16
System.out.println(str.length()); //16
str.append("1");
System.out.println(str.capacity()); //34
System.out.println(str.length()); //17
str = new StringBuffer("123");
System.out.println(str.capacity()); //19
System.out.println(str.length()); //3
}
}
先看代码第5行,StringBuffer str = new StringBuffer();
//创建一个StringBuffer对象,默认大小为16
当append()字符串小于16的时候,调用str.capacity()方法查看容量大小为16,str.length()大小为你添加字符串的长度
当你添加的字符串超过16的时候,StringBuffer会自动扩容到原来容量的2倍+2
str = new StringBuffer("123");
此时StringBuffer的容量不再是扩容2倍+2,而是直接由原来容量(即默认容量)+字符串长度