Java Reference
In-Depth Information
in a
StringBuilder
without allocating more memory, respectively. Method
ensure-
Capacity
guarantees that a
StringBuilder
has at least the specified capacity. Method
setLength
increases or decreases the length of a
StringBuilder
. Figure 14.11 demon-
strates these methods.
1
// Fig. 14.11: StringBuilderCapLen.java
2
// StringBuilder length, setLength, capacity and ensureCapacity methods.
3
4
public class
StringBuilderCapLen
5
{
6
public
static
void
main(String[] args)
7
{
8
StringBuilder buffer =
new
StringBuilder(
"Hello, how are you?"
);
9
10
System.out.printf(
"buffer = %s%nlength = %d%ncapacity = %d%n%n"
,
11
buffer.toString(),
buffer.length() buffer.capacity()
,
);
12
13
buffer.ensureCapacity(
75
);
14
System.out.printf(
"New capacity = %d%n%n"
,
buffer.capacity()
);
15
16
buffer.setLength(
10
));
17
System.out.printf(
"New length = %d%nbuffer = %s%n"
,
18
buffer.length()
, buffer.toString());
19
}
20
}
// end class StringBuilderCapLen
buffer = Hello, how are you?
length = 19
capacity = 35
New capacity = 75
New length = 10
buffer = Hello, how
Fig. 14.11
|
StringBuilder
length
,
setLength
,
capacity
and
ensureCapacity
methods.
The application contains one
StringBuilder
called
buffer
. Line 8 uses the
String-
Builder
constructor that takes a
String
argument to initialize the
StringBuilder
with
"Hello,
how
are
you?"
. Lines 10-11 print the contents, length and capacity of the
StringBuilder
. Note in the output window that the capacity of the
StringBuilder
is ini-
tially 35. Recall that the
StringBuilder
constructor that takes a
String
argument initial-
izes the capacity to the length of the string passed as an argument plus 16.
Line 13 uses method
ensureCapacity
to expand the capacity of the
StringBuilder
to a minimum of 75 characters. Actually, if the original capacity is less than the argument,
the method ensures a capacity that's the greater of the number specified as an argument
and twice the original capacity plus 2. The
StringBuilder
's current capacity remains
unchanged if it's more than the specified capacity.