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

Viewed 2151

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

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());
2 Answers

By using a char array. You can see this in the JDK source. In JDK 1.8 (the one I have the source for handy), StringBuilder is built on top of AbstractStringBuilder which uses this to hold the data:

char[] value;
int    count;

(Karol Dowbecki says that JDK 9 "sometimes" uses byte instead of char; I have no reason to doubt him. :-) )

count tells the class how much of value is actual data vs. just available space in the array. It starts out with a char[16] (unless you tell it in advance what capacity you may require) and reallocates and copies as needed.

It only creates a string when you call toString, using the String(char[],int,int) constructor (or presumably one accepting byte[] sometimes JDK9) to make a copy of the portion of the array's contents that are actually used:

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

Behind the scene it uses a char[] (or byte[] in JDK 9 or newer) to store the characters. New String object is created only after calling StringBuilder.toString().

Related