Java Reference
In-Depth Information
Performance Tip 14.5
Dynamically increasing the capacity of a
StringBuilder
can take a relatively long time.
Executing a large number of these operations can degrade the performance of an applica-
tion. If a
StringBuilder
is going to increase greatly in size, possibly multiple times, setting
its capacity high at the beginning will increase performance.
Line 16 uses method
setLength
to set the length of the
StringBuilder
to 10. If the
specified length is less than the current number of characters in the
StringBuilder
, its
contents are truncated to the specified length (i.e., the characters in the
StringBuilder
after the specified length are discarded). If the specified length is greater than the number
of characters currently in the
StringBuilder
,
null
characters (characters with the
numeric representation 0) are appended until the total number of characters in the
StringBuilder
is equal to the specified length.
reverse
Class
StringBuilder
provides methods
charAt
,
setCharAt
,
getChars
and
reverse
to ma-
nipulate the characters in a
StringBuilder
(Fig. 14.12). Method
charAt
(line 12) takes an
integer argument and returns the character in the
StringBuilder
at that index. Method
getChars
(line 15) copies characters from a
StringBuilder
into the character array passed
as an argument. This method takes four arguments—the starting index from which charac-
ters should be copied in the
StringBuilder
, the index one past the last character to be copied
from the
StringBuilder
, the character array into which the characters are to be copied and
the starting location in the character array where the first character should be placed. Method
setCharAt
(lines 21 and 22) takes an integer and a character argument and sets the character
at the specified position in the
StringBuilder
to the character argument. Method
reverse
(line 25) reverses the contents of the
StringBuilder
. Attempting to access a character that's
outside the bounds of a
StringBuilder
results in a
StringIndexOutOfBoundsException
.
1
// Fig. 14.12: StringBuilderChars.java
2
// StringBuilder methods charAt, setCharAt, getChars and reverse.
3
4
public class
StringBuilderChars
5
{
6
public static void
main(String[] args)
7
{
8
StringBuilder buffer =
new
StringBuilder(
"hello there"
);
9
10
System.out.printf(
"buffer = %s%n"
, buffer.toString());
11
System.out.printf(
"Character at 0: %s%nCharacter at 4: %s%n%n"
,
12
buffer.charAt(
0
) buffer.charAt(
4
)
,
);
13
14
char
[] charArray =
new
char[buffer.length()];
15
buffer.getChars(
0
, buffer.length(), charArray,
0
);
16
System.out.print(
"The characters are: "
);
Fig. 14.12
|
StringBuilder
methods
charAt
,
setCharAt
,
getChars
and
reverse
. (Part 1
of 2.)