Is StringBuilder's setLength method a redundant assignment of \ 0 to an array of char [] values?

I am creating a Java StringBuilder setLength method .

If the new length is greater, it sets the new "added" 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 it superfluous? The expandCapacity (newLength) method Arrays.copyOf 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 default values. For char, this is "\ u0000", which I understand is the Unicode equivalent of "\ 0".

Also, the documentation of StringBuilder setLength says:

If newLength is greater than or equal to the current length, sufficient null characters ('\ u0000') are appended so that length becomes newLength.

But the length of this array can be obtained directly without assigning values ​​to its components:

char[] array = new char[10];
System.out.println(array.length); // prints "10"

      

So, is the for-loop a redundant setLength value?

+3


source to share


1 answer


This is necessary when we want to reuse StringBuilder

.

Suppose we remove this code in StringBuilder

  if (count < newLength) {
         for (; count < newLength; count++)
             value[count] = '\0';
     }

      



And we are testing the code below:

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 you mentioned in jdk6 is different in java8.

+1


source







All Articles