Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Consider how StringBuffer is typically used. When the String we need to store in a StringBuffer exceeds the current capacity, the current capacity is increased. If the algorithm only increased the capacity to the required amount, then StringBuffer would be very inefficient. For example:</p> <pre><code> buf.append(someText); buf.append(someMoreText); buf.append(Another100Chars); </code></pre> <p>might require that the capacity be increased three times in a row. Every time the capacity is increased, the underlying data structure (an array) needs to be re-allocated in memory, which involves allocating more RAM from the heap, copying the existing data, and then eventually garbage collecting the previously allocated memory. To reduce the frequency of this happening, StringBuffer will double its capacity when needed. The algorithm moves the capacity from n to 2n+2. Here is the source code from AbstraceStringBuilder where this method is implemented:</p> <pre><code>/** * This implements the expansion semantics of ensureCapacity with no * size check or synchronization. */ void expandCapacity(int minimumCapacity) { int newCapacity = value.length * 2 + 2; if (newCapacity - minimumCapacity &lt; 0) newCapacity = minimumCapacity; if (newCapacity &lt; 0) { if (minimumCapacity &lt; 0) // overflow throw new OutOfMemoryError(); newCapacity = Integer.MAX_VALUE; } value = Arrays.copyOf(value, newCapacity); } </code></pre> <p>Every time you append to a StringBuffer or call setLength, this method is called:</p> <pre><code>public synchronized void ensureCapacity(int minimumCapacity) { if (minimumCapacity &gt; value.length) { expandCapacity(minimumCapacity); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload