在 Java 中,字串字面值屬於 String 類。雖然字元陣列也能表示字串,但 Java 編譯器將字串字面值視為 String 物件。String 物件一旦建立即不可變更。若需進行大量字串修改操作,應優先使用 StringBuilder 或 StringBuffer,最終再轉換為 String。
StringBuffer 類似於 String,但提供可變的字串緩衝區。透過方法呼叫可改變序列長度與內容。每個緩衝區擁有特定容量,若字元序列長度未超出容量,無需分配新陣列;若溢出,容量會自動擴大。其所有公開方法均以 synchronized 修飾,保證執行緒安全,但也帶來效能開銷。
自 JDK 1.5 起,StringBuilder 作為 StringBuffer 的非同步等價類登場。它支援所有相同操作,但因不執行同步,速度顯著更快。單執行緒環境下應優先使用 StringBuilder。
常用方法包括:length()、capacity()、append()、insert()、indexOf()、lastIndexOf()、reverse()、toString() 等。
public class StringBuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
sb.append("hello").append(1).append(1.5).append(true);
System.out.println("長度: " + sb.length());
System.out.println("容量: " + sb.capacity());
sb.insert(5, "world");
System.out.println(sb.toString()); // helloworld11.5true
sb.replace(5, 7, "el");
System.out.println(sb.toString()); // helloelrld11.5true
System.out.println("首次出現 'el' 索引: " + sb.indexOf("el"));
System.out.println("反轉: " + sb.reverse());
}
}
透過封裝字元陣列,手動實現動態擴容、追加、長度統計與字串轉換等核心邏輯,深入理解 StringBuilder 底層原理。
import java.util.Arrays;
public class MyStringBuilderDemo {
public static void main(String[] args) {
MyStringBuilder msb = new MyStringBuilder();
msb.append("hello").append("java").append("12345678");
System.out.println("字元個數: " + msb.length());
System.out.println("總容量大小: " + msb.capacity());
System.out.println("輸出字串: " + msb.toString());
}
}
class MyStringBuilder {
private char[] value; // 底層字元陣列
private int count = 0; // 實際字元數
public MyStringBuilder() { this.value = new char[16]; }
public MyStringBuilder(int capacity) { this.value = new char[capacity]; }
public MyStringBuilder(String str) { this.value = new char[str.length() + 16]; }
public int length() { return count; }
public int capacity() { return value.length; }
// 核心追加邏輯:確保容量 -> 複製字元 -> 更新計數 -> 返回 this 支援鏈式呼叫
public MyStringBuilder append(String str) {
int len = str.length();
ensureCapacity(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
private void ensureCapacity(int capacity) {
if (capacity - value.length > 0) {
int newCapacity = value.length * 2 + 2;
value = Arrays.copyOf(value, newCapacity);
}
}
public String toString() { return new String(value, 0, count); }
}
此實現展示了動態陣列擴容 (2倍+2)、字元複製與鏈式呼叫設計模式,是理解 JDK 內建類別原理的優秀切入點。