StringBuffer 初始能容纳16个字符- public StringBuffer() {
- super(16);
- }
复制代码 若超过长度,会自动调用如下方法:- */
- 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);
- }
复制代码 也就是说他的新长度=旧长度×2+2;
测试一下:- package test;
- public class Test {
- public static void main(String[] args) {
- StringBuffer sb = new StringBuffer();
-
- System.out.println(sb.capacity() );
-
- sb.append("01234567890123456790");
- System.out.println(sb.capacity() );
- }
- }
复制代码 output: |