StringBuffer和StringBuilder都继承于AbstractStringBuilder,底层为char数组实现的,两者都是使用AbstractStringBuilder的
两者都调用AbstractStringBuilder类的append方法
如果容量超过16时,按照(原来的大小+1)* 2 进行扩容
构造函数初始化的,默认大小是16。
构造函数如下:
AbstractStringBuilder(int capacity) { value = new char[capacity]; }StringBuffer的append方法上面有synchronized关键字修饰,是线程安全的,StringBuilder没有synchronized关键字修饰,是线程不安全的,
两者都调用AbstractStringBuilder类的append方法
如果容量超过16时,按照(原来的大小+1)* 2 进行扩容
public AbstractStringBuilder append(String str) { if (str == null) str = "null"; int len = str.length(); if (len == 0) return this; int newCount = count + len; //获取新的这次添加元素后的数组大小 if (newCount > value.length) //如果本次的大小大于数组的长度则扩容 expandCapacity(newCount); str.getChars(0, len, value, count); //把str字符串 复制到value数组中 count = newCount; return this; }
void expandCapacity(int minimumCapacity) { int newCapacity = (value.length + 1) * 2; //扩容按照 (原来的大小+1)*2 if (newCapacity < 0) { newCapacity = Integer.MAX_VALUE; } else if (minimumCapacity > newCapacity) { newCapacity = minimumCapacity; } char newValue[] = new char[newCapacity]; //创建一个新数组 System.arraycopy(value, 0, newValue, 0, count); //把旧数组复制到新的数组 value = newValue; }