如何实现 StringBuilder 来避免不可变字符串分配问题?

How is a StringBuilder implemented to avoid the immutable string allocation problem?

如何实现 StringBuilder 来避免不可变字符串分配问题?

StringBuilder aliasA = new StringBuilder("a");
StringBuilder dot = new StringBuilder(".");
Clausula clause1 = new Clausula(aliasA.append(dot).append("id").toString());
Clausula clause2 = new Clausula(aliasA.append(dot).append("name").toString());

在幕后,它使用 char[](或 JDK 9 或更新版本中的 byte[])来存储字符。仅在调用 StringBuilder.toString().

后创建新的 String 对象

通过使用 char 数组。您可以在 JDK 来源中看到这一点。在 JDK 1.8(我手头有源代码的那个)中,StringBuilder 建立在 AbstractStringBuilder 之上,它使用它来保存数据:

char[] value;
int    count;

( 那 JDK 9 "sometimes" 使用 byte 而不是 char;我没有理由怀疑他。:-) )

count 告诉 class 有多少 value 是实际数据与数组中仅可用的 space。它以 char[16] 开头(除非您事先告诉它您可能需要什么容量)并根据需要重新分配和复制。

它只在你调用 toString 时创建一个字符串,使用 String(char[],int,int) constructor(或者大概是接受 byte[] 有时 JDK9)来复制实际使用的数组内容部分:

public String toString() {
    // Create a copy, don't share the array
    return new String(value, 0, count);
}