StringBuffer 是**執行緒安全**的可變字串序列(所有 public 方法加 synchronized),適用於多執行緒環境。JDK 5 引入 StringBuilder,**API 相同但非同步**,單執行緒下效能更高,現代開發**優先使用 StringBuilder**。
| 分類 | 方法簽名 | 說明 |
|---|---|---|
| 新增/插入 | append(...) | 尾端追加,支援所有基本型別、物件、CharSequence,回傳 this 可鏈式 |
insert(offset, ...) | 指定位置插入,同支援多型別 | |
| 刪除 | delete(start, end) | 刪除 [start, end) 區間字元 |
deleteCharAt(index) | 刪除單一字元 | |
| 修改 | setCharAt(index, ch) | 替換單一字元 |
replace(start, end, str) | 以 str 取代 [start, end) 區間 | |
| 查詢 | charAt(index) / indexOf(str) / lastIndexOf(str) | 單字元存取、子字串搜尋 |
substring(start[, end]) | 擷取子字串 (不影響原序列) | |
| 容量控制 | capacity() / ensureCapacity(min) / setLength(len) | 內部陣列容量管理,擴容策略約 2n+2 |
| 反轉/轉換 | reverse() / toString() / getChars(srcBeg, srcEnd, dst[], dstBeg) | 就地反轉、轉不可變 String、複製到 char 陣列 |
public class StringBufferDemo {
public static void main(String[] args) {
// 1. 建構與容量
StringBuffer sb = new StringBuffer(16); // 預設容量 16
sb.append("Hello").append(" ").append("World");
System.out.println("內容: " + sb); // Hello World
System.out.println("長度: " + sb.length()); // 11
System.out.println("容量: " + sb.capacity()); // ≥11
// 2. 插入與替換
sb.insert(5, ",");
System.out.println("插入逗號: " + sb); // Hello, World
sb.replace(0, 5, "Hi");
System.out.println("替換前綴: " + sb); // Hi, World
// 3. 刪除
sb.delete(3, 4); // 刪除逗號
System.out.println("刪除逗號: " + sb); // Hi World
// 4. 反轉
sb.reverse();
System.out.println("反轉: " + sb); // dlroW iH
// 5. 複製到 char 陣列
char[] buf = new char[20];
sb.getChars(0, sb.length(), buf, 5);
System.out.println("陣列內容: " + new String(buf)); // " dlroW iH "
// 6. 設定長度 (截斷或補 \0)
sb.setLength(5);
System.out.println("截斷長度5: [" + sb + "]"); // [dlroW]
}
}
// 單執行緒 100 萬次 append
long t1 = System.nanoTime();
StringBuffer sbf = new StringBuffer();
for (int i=0; i<1_000_000; i++) sbf.append('a');
System.out.println("StringBuffer: " + (System.nanoTime()-t1)/1e6 + " ms");
long t2 = System.nanoTime();
StringBuilder sbl = new StringBuilder();
for (int i=0; i<1_000_000; i++) sbl.append('a');
System.out.println("StringBuilder: " + (System.nanoTime()-t2)/1e6 + " ms");
典型輸出:StringBuffer: 45 ms vs StringBuilder: 12 ms(差距約 3-4 倍,源自同步開銷)。
ThreadLocal 避免鎖)。StringBuffer 參數 → 傳 stringBuilder.toString() 或轉型(極少見)。