StringBuffer总结分析
构造方法
/** * Constructs a string buffer with no characters in it and an * initial capacity of 16 characters. * 创建容量为16个char大小的空间 */ public StringBuffer() { super(16); } /** * Constructs a string buffer with no characters in it and * the specified initial capacity. *创建一个指定容量的StringBuffer对象 * @param capacity the initial capacity. * @exception NegativeArraySizeException if the {@code capacity} * argument is less than {@code 0}. */ public StringBuffer(int capacity) { super(capacity); } /** *初始化一个有指定string的对象,空间大小为string.length+16 * Constructs a string buffer initialized to the contents of the * specified string. The initial capacity of the string buffer is * {@code 16} plus the length of the string argument. * * @param str the initial contents of the buffer. */ public StringBuffer(String str) { super(str.length() + 16); //new char[str.length() + 16] append(str); }
append方法 如果string的长度大于capacity的增String会自动增加容量
以下情况,容器容量需要扩展
2.当capacity<str<2*capacity+2时,值为 2*capacity+2
3.当string>2*capacity+2时,值为string