Tuesday, December 20, 2011

Java's character and assorted string classes support text-processing - 20


  • public void ensureCapacity(int minimumCapacity) ensures the current StringBuffer's current capacity is larger than minimumCapacity and twice the current capacity. If minimumCapacity is negative, this method returns without doing anything. The following code demonstrates this method:
·         StringBuffer sb = new StringBuffer ("abc");
·         System.out.println (sb.capacity ());
·         sb.ensureCapacity (20);
·         System.out.println (sb.capacity ());

The fragment produces the following output:

19
40
·  Tip
Because it takes time for a StringBuffer to create a new character array and copy characters from the old array to the new array (during an expansion), use ensureCapacity(int minimumCapacity) to minimize expansions prior to entering a loop that appends many characters to a StringBuffer. That improves performance.

No comments: