StringBuffer insert method using capacity as parameter

public class example{
    public static void main(String args[]) {
       StringBuffer s1 = new StringBuffer(10);
       s1.insert(0,avaffffffffffffffffffffffffffffffffffffffffffvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
       System.out.println(s1);
    }
}

      

the output of this code is as follows avaffffffffffffffffffffffffffffffffffffffffffvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

.

what is the use of parameter 10 in a method of the StringBuffer class? if 10 is the size of the buffer and 0 is the offset of the insert method, how do we get the entire string as output?

+3


source to share


3 answers


From JavaDoc:

A string buffer is similar to a String, but it can be modified. At any point in time contains a specific sequence of characters, but the length and content of the sequence can be changed through a specific method call



10 is just the initial capacity (continue reading JavaDoc):

Each row buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, there is no need to allocate a new internal buffer array. If the internal buffer overflows, it automatically grows larger.

+2


source


Read the docs :

capacity - initial capacity.



So it's not "size".

0


source


what is the use of parameter 10 in a method of the StringBuffer class? if 10 is the size of the buffer and 0 is the offset of the insert method, how do we get the entire string as output?

The answer is that you can reduce the original capacity if you know it is unlikely to be used up. When a string buffer is created, memory must be allocated. The default size is 16, but if you only want to use it for one character, you can specify that the initial capacity is 1, and since it will only change when more than one character is added to it, you can avoid wasting memory.

The same goes for parameters in things like HashSet (n). It will resize if you add items too, but if you know exactly how many items you will have, you can save a little memory and operations needed to resize by sizing it exactly.

0


source







All Articles