简体   繁体   中英

setLength() method is StringBuilder and how it works internally

As far as I understand, a StringBuilder object contains an array of characters. And when we construct a StringBuilder object, we specify a capacity(or directly provide a string). I'm assuming this means an array of the specified capacity length(or default capacity) is also created internally.

If I then append or insert a string of shorter length than the capacity, what's in the (leftover?) empty slots of that array? Is it null(\)?

And if it is null, what happens with setLength(newLength) when the newLength argument is greater than the length of the actual string also confuses me. In the java API documentation, it is stated that "If the newLength argument is greater than or equal to the current length, sufficient null characters(\) are appended to the string builder so that "length" becomes the newLength argument." My question is, aren't there null characters there already?

Any clarifications are appreciated (:

Edit again: meant in* in the title

My question is, aren't there null characters there already?

No, when you shrink or delete chars from the StringBuilder it doesn't have to pad out the chars no longer used with nul chars.

According to javadoc of SpringBuilder :

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

So in fact as StringBuilder stores array of char characters, this array will be length of newLength .

If your current StringBuilder has length 10, and you set this length to 12, the missing space will be filled by null (for char type this is \ ). So the two last chars will be null.

StringBuilder sb = new StringBuilder();
sb.append('x');
System.out.println(sb.length()); // prints 1
sb.setLength(2);
System.out.println(sb.length()); // prints 2

Suppose StringBuilder has an array of length 'n', and 'k' for the new length.
My understanding is then as follows:

  • if k>n, then null values ('\') will be appended to fit the length increase
  • If k == n, nothing will happen. JavaDoc says "greater than or equal to the current length", but I am not sure anything will happen if the current length is the same as the new length.
  • If k < n, the array will be shortened to length k, no null-characters will be added.

The null characters are added by StringBuilder. setLength does the following:

First, use the Arrays copy.

Arrays.copyOf(value, newLength)

and last, set \\0 on the last characters:

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

if you look at the code of setLength method of string builder it does the following

  1. ensures new length is positive else throw StringIndexOutOfBoundsException

  2. ensures that minimum capacity is met for example if the min capacity was 10 and you are changing length to 20, a new array is created and content of the actual array is copied to it this new array, then it replaces the old array of the string builder. no new array is created if length is being reduced

  3. it checks if the length of the new array is more than the previous array, if yes then it fills the extra indexes of that array with null character

  4. sets the length of the new array as the current length ( In case the new length is less than the previous length the extra characters are discarded, In short the array is not altered or replaced just the length marker of the array is changed to new length)

  • If the newLength argument is greater than or equal to the current length, sufficient null characters ('\') are appended so that length becomes the newLength argument.
  • Execute these set of commands to understand the behaviour of setLength() method

     StringBuilder str = new StringBuilder("tutorials"); System.out.println("string = " + str); // length of StringBuilder System.out.println("length = " + str.length()); // set the length of StringBuilder to 5 str.setLength(5); // print new StringBuilder value after changing length System.out.println("After set, string = " + str); // length of StringBuilder after changing length System.out.println("length = " + str.length());

Output:

string = tutorials
length = 9
After set, string = tutor
length = 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM