13.4.3. Capacity Management
The buffer of a StringBuilder object has a capacity, which is the length of the string it can store before it
must allocate more space. The buffer grows automatically as characters are added, but it is more efficient to
specify the size of the buffer only once.
You set the initial size of a StringBuilder object by using the constructor that takes a single int:
publicStringBuilder(int capacity)
Constructs a StringBuilder with the given initial capacity and an
initial value of "".
public voidensureCapacity(int minimum)
Ensures that the capacity of the buffer is at least the specified minimum.
public intcapacity()
Returns the current capacity of the buffer.
public voidtrimToSize()
Attempts to reduce the capacity of the buffer to accommodate the current
sequence of characters. There is no guarantee that this will actually reduce
the capacity of the buffer, but this gives a hint to the system that it may be a
good time to try and reclaim some storage space.
You can use these methods to avoid repeatedly growing the buffer. Here, for example, is a rewrite of the
sqrtInt method from page 332 that ensures that you allocate new space for the buffer at most once:
String sqrtIntFaster(int i) {
StringBuilder buf = new StringBuilder(50);
buf.append("sqrt(").append(i).append(')');
buf.append(" = ").append(Math.sqrt(i));
return buf.toString();
}
The only change is to use a constructor that creates a StringBuilder object large enough to contain the
result string. The value 50 is somewhat larger than required; therefore, the buffer will never have to grow.
13.4.4. The StringBuffer Class
The StringBuffer class is essentially identical to the StringBuilder class except for one thing: It
provides a thread-safe implementation of an appendable character sequencesee Chapter 14 for more on thread
safety. This difference would normally relegate discussion of StringBuffer to a discussion on thread-safe
data structures, were it not for one mitigating factor: The StringBuffer class is older, and previously
filled the role that StringBuilder does now as the standard class for mutable character sequences. For
this reason, you will often find methods that take or return StringBuffer rather than StringBuilder,
CharSequence, or Appendable. These historical uses of StringBuffer are likely to be enshrined in
the existing APIs for many years to come.