The reverseIt
method uses StringBuffer
's
append
method to
add a character to the end of the destination string: dest
.
class ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i--) {
dest.append(source.charAt(i));
}
return dest.toString();
}
}
If the appended character causes the size of the StringBuffer
to grow
beyond its current capacity, the StringBuffer
allocates more memory.
Because memory allocation is a relatively expensive operation, you can make
your code more efficient by initializing a StringBuffer
's capacity to a
reasonable first guess, thereby minimizing the number of times memory
must be allocated for it. For example, the reverseIt
method
constructs the StringBuffer
with an initial capacity equal to the length
of the source string, ensuring only one memory allocation for dest
.
The version of the append
method used in reverseIt
is only one of the StringBuffer
methods that appends data to the end of a
StringBuffer
. There are several append
methods that append
data of various types, such as float
, int
, boolean
,
and even Object
, to the end of the StringBuffer
. The data is
converted to a string before the append operation takes place.