重点在于AbstractStringBuilder.append(String str)方法(StringBuilder,StringBuffer中的append方法都是继承调用这个方法的 ,只不过StringBuffer的append方法是synchronized修饰的),源码如下:
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;
}
其中“ensureCapacityInternal(count+len)"用于计算数组是否需要进行扩容,源码如下:
private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0) {
value = Arrays.copyOf(value,
newCapacity(minimumCapacity));
}
}
如果新字符串长度超过了 原来字符数组的大小,那么需要使用Arrays.copyOf进行扩容,返回一个新数组。
然后 str.getChars(0, len, value, count);的作用是将新数据(str)的内容存放到数组(value中),源码如下
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
if (srcBegin < 0) {
throw new StringIndexOutOfBoundsException(srcBegin);
}
if (srcEnd > value.length) {
throw new StringIndexOutOfBoundsException(srcEnd);
}
if (srcBegin > srcEnd) {
throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
}
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
这个方法主要负责调用System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length),来进行内容复制
每一个参数作用:将src数组内容从srcPos开始截取 然后 追加到dest数组的destPos位置后,共追加length个元素
总结两个数组复制方法的区别:
①Arrays.copyOf返回值是一个新数组,即这个过程产生了新数组,但数据没有改变。
②System.arraycopy没有返回值,且这个过程没有产生新数组,只是将一个旧数组内容放到新数组内容之中,数据发生了改变。
当你需要数组扩容,那么应该使用Arrays.copyOf,如果你想将将一个数组内容复制到另一个数组内容,那么应该使用System.arraycopy。