我们从源码来分析一下StringBuilder的底层原理:
/*** Constructs a string builder with no characters in it and an* initial capacity of 16 characters.*/public StringBuilder() {super(16);}
定义一个无参的StringBuilder时,初始化容量为16.例如:StringBuilder sb = new StringBuilder();
/*** Constructs a string builder with no characters in it and an* initial capacity specified by the {@code capacity} argument.** @param capacity the initial capacity.* @throws NegativeArraySizeException if the {@code capacity}* argument is less than {@code 0}.*/public StringBuilder(int capacity) {super(capacity);}
定义参数为整数大小StringBuilder时,调用父类(AbstractStringBuilder)的初始化方法。例如:StringBuilder sb = new StringBuilder(5);
/*** Creates an AbstractStringBuilder of the specified capacity.*/AbstractStringBuilder(int capacity) {value = new char[capacity];}
AbstractStringBuilder的构造方法就是建立一个容量与参数大小一致的对象。
当参数为一个字符串时,例如:StringBuilder sb = new StringBuilder("abcdefghj")时
public StringBuilder(String str) {super(str.length() + 16);append(str);}
大小为16加上参数字符串的大小。
接下来我们来看看StringBuilder的扩容机制
当上面调用有字符串参数的构造方法时,底层调用了一个append()方法
public AbstractStringBuilder append(String str) {if (str == null)return appendNull();int len = str.length();ensureCapacityInternal(count + len);str.getChars(0, len, value, count);count += len;return this;}
append()方法如上所示,我们需要判断容量是否足够,通过ensureCapacityInternal()方法
private void ensureCapacityInternal(int minimumCapacity) {// overflow-conscious codeif (minimumCapacity - value.length > 0) {value = Arrays.copyOf(value,newCapacity(minimumCapacity));}}
value表示的是现在的字符串容量大小,当我们现在需要存的字符串大小大于原理的容量,进行复制扩容,调用了newCapacity()方法
private int newCapacity(int minCapacity) {// overflow-conscious codeint newCapacity = (value.length << 1) + 2;if (newCapacity - minCapacity < 0) {newCapacity = minCapacity;}return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)? hugeCapacity(minCapacity): newCapacity;}private int hugeCapacity(int minCapacity) {if (Integer.MAX_VALUE - minCapacity < 0) { // overflowthrow new OutOfMemoryError();}return (minCapacity > MAX_ARRAY_SIZE)? minCapacity : MAX_ARRAY_SIZE;}
底层会先把容量大小扩充为原来大小的2倍+2,如果还不够,则调用hugeCapacity()直接把容量大小扩展为需要的容量大小。