Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder capacity()

I noticed that the capacity method returns StringBuilder capacity without a logic way ... sometime its value is equals to the string length other time it's greater...

is there an equation for know which is its logic?

like image 283
xdevel2000 Avatar asked Jul 06 '10 07:07

xdevel2000


People also ask

What is capacity in StringBuilder?

Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is 16 plus the length of the string argument.

What is capacity () in Java?

The capacity () method is a part of the StringBuffer class. It basically denotes the amount of space available to store new characters. The method returns the current capacity of the string buffer. By default, an empty StringBuffer contains 16 character capacity.

How do I find the size of a StringBuilder?

The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method.

How many characters can a StringBuilder hold?

The default capacity of a StringBuilder object is 16 characters, and its default maximum capacity is Int32.


1 Answers

When you append to the StringBuilder, the following logic happens:

if (newCount > value.length) {
    expandCapacity(newCount);
}

where newCount is the number of characters needed, and value.length is the current size of the buffer.

expandCapacity simply increases the size of the backing char[]

The ensureCapacity() method is the public way to call expandCapacity(), and its docs say:

Ensures that the capacity is at least equal to the specified minimum. If the current capacity is less than the argument, then a new internal array is allocated with greater capacity. The new capacity is the larger of:

  • The minimumCapacity argument.
  • Twice the old capacity, plus 2.

If the minimumCapacity argument is nonpositive, this method takes no action and simply returns.

like image 67
Bozho Avatar answered Oct 22 '22 18:10

Bozho