標籤:io java ar for 資料 sp on 代碼 c
public synchronized StringBuffer append(String str) {
super.append(str);
return this;
} // 同步方法
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
ensureCapacityInternal(count + len); // 是否擴容數組,如果擴容,返回將原資料拷入進去的數組
str.getChars(0, len, value, count); // 將str拷貝進數組
count += len;
return this;
}
private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0) // 原數組中資料內容長度+ 新需要拷貝的字串長度超過原數組長度需要擴容
expandCapacity(minimumCapacity);
}
void expandCapacity(int minimumCapacity) {
int newCapacity = value.length * 2 + 2; // 擴容按照原數組長度的2 * len + 2 的比例
if (newCapacity - minimumCapacity < 0)
newCapacity = minimumCapacity; // 在需要append的字串很長的情況下會出現
if (newCapacity < 0) { // oom
if (minimumCapacity < 0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
value = Arrays.copyOf(value, newCapacity); // 將原資料拷貝進一個擴容後的數組返回
}
參考原始碼,自己在工程代碼中簡單實現了功能.
byte[] bytes = new byte[16]; // StringBuff原始碼預設初始化是16位元組
String str = "hellowewewehellowewewe"; //
bytes = Arrays.copyOf(bytes, 100); // 簡單擴容, 省略了判斷
str.getBytes(0, str.length(), bytes, 0);
System.out.println(bytes);
for (int i = 0; i < 100; i++){
System.out.println(bytes[i]);
}
java 中 Stringbuff append原始碼淺析