Java Reference
In-Depth Information
A StringBuffer or StringBuilder object's internal array is associated with
the concepts of capacity and length. Capacity refers to the maximum number of char-
actersthatcanbestoredinthearraybeforethearraygrowstoaccommodateadditional
characters. Length referstothenumberofcharactersthatarealreadystoredinthearray.
The toAlignedBinaryString() method presented earlier in this chapter in-
cluded the following inefficient loop in its implementation:
int numLeadingZeros = numBits-result.length();
String zerosPrefix = "";
for (int j = 0; j < numLeadingZeros; j++)
zerosPrefix += "0";
This loop is inefficient because each of the iterations creates a StringBuilder
objectanda String object.Thecompilertransformsthiscodefragmentintothefol-
lowing fragment:
int numLeadingZeros = 3;
String zerosPrefix = "";
for (int j = 0; j < numLeadingZeros; j++)
zerosPrefix = new StringBuild-
er().append(zerosPrefix).append("0").toString();
A more efficient way to code the previous loop involves creating a
StringBuffer / StringBuilder object prior to entering the loop, calling the ap-
propriate append() methodintheloop,andcalling toString() aftertheloop.The
following code fragment demonstrates this more efficient scenario:
int numLeadingZeros = 3;
StringBuilder sb = new StringBuilder();
for (int j = 0; j < numLeadingZeros; j++)
sb.append("0");
String zerosPrefix = sb.toString();
Search WWH ::




Custom Search