頻繁字符串修改場景下,String 不可變導致大量對象創建。StringBuilder(非線程安全、高性能)與 StringBuffer(線程安全、有鎖開銷)API 幾乎一致,單線程首選 StringBuilder。
char[] value; // 底層字符數組,非 final,可修改
int count; // 實際使用字符數
public StringBuilder() { super(16); } // 默認 16 字符
public StringBuilder(int capacity) { super(capacity); }
public StringBuilder(String str) { super(str.length() + 16); append(str); }
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
ensureCapacityInternal(count + len); // 確保容量
str.getChars(0, len, value, count); // 複制字符
count += len;
return this;
}
int newCapacity = value.length * 2 + 2;
if (newCapacity - minimumCapacity < 0) newCapacity = minimumCapacity;
value = Arrays.copyOf(value, newCapacity);
new StringBuilder(estimatedSize) 避免多次擴容public String toString() {
return new String(value, 0, count); // 新建 String,不共享數組,保證不可變性
}
System.arraycopy(value, offset, value, offset + len, count - offset); // 向後挪動
str.getChars(value, offset); // 填入新字符
count += len;
System.arraycopy 為 native 方法(C++ 實現),支援同數組源目重疊複製,效率極高。
System.arraycopy(value, start + len, value, start, count - end);
count -= len;
delete(start, end);
insert(start, str);
非簡單 char[] 反轉,對補充字符(> 0xFFFF)雙 char 做二次修正,保證字符有效性。
支援 boolean, char, int, long, float, double, Object, CharSequence, char[] 等所有基本類型與常見對象,內部統一轉字符後調用核心 append(String)。
char[] + count 設計,變長數組思想Arrays.copyOf 實現System.arraycopy 高效移動數據toString() 防禦性複製保證 String 不可變StringBuffer 或 ThreadLocal 隔離