I'm stuyding the Java StringBuilder's setLength method.
If the new length is larger, it sets the newly "appended" array indices to '\0':
public void setLength(int newLength) {
if (newLength < 0)
throw new StringIndexOutOfBoundsException(newLength);
if (newLength > value.length)
expandCapacity(newLength);
if (count < newLength) {
for (; count < newLength; count++)
value[count] = '\0';
} else {
count = newLength;
}
}
Is this unnecessary? In expandCapacity(newLength) the Arrays.copyOf method is used to create a new char[] array with size newLength:
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
The Java language specification states that components in arrays are initialized to their default values. For char, this is '\u0000' which I understand to be the unicode equivalent of '\0'.
Additionally, the StringBuilder setLength documentation states:
If the newLength argument is greater than or equal to the current length, sufficient null characters ('\u0000') are appended so that length becomes the newLength argument.
But the length of this array can be accessed directly without assigning values to its components:
char[] array = new char[10];
System.out.println(array.length); // prints "10"
So, is the for-loop in setLength redundant?
It is necessary when we want to reuse StringBuilder.
Assume we remove this code in StringBuilder
if (count < newLength) {
for (; count < newLength; count++)
value[count] = '\0';
}
And we test with below code:
StringBuilder builder = new StringBuilder("test");
builder.setLength(0); //the `value` still keeps "test", `count` is 0
System.out.println(builder.toString()); //print empty
builder.setLength(50); //side effect will happen here, "test" is not removed because expandCapacity still keeps the original value
System.out.println(builder.toString()); // will print test
The code your mention is in jdk6, in java8 is different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With