Java Reference
In-Depth Information
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.
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
ob-
ject 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 ap-
pendable 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 se-
quences. 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
API
s for many years to come.