/**
* The value is used for character storage. */ char[] value;
|
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; }
|
/**
* This method has the same contract as ensureCapacity, but is * never synchronized. */ private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code
//判斷容量是否夠用
if (minimumCapacity - value.length > 0)expandCapacity(minimumCapacity); }
|
/**
* This implements the expansion semantics of ensureCapacity with no * size check or synchronization. */ void expandCapacity(int minimumCapacity) {
//每次擴容使原有的2倍加2
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);
}
|