1.6 Adding StringBuilder to the Mix
As you work through this book, you'll find that in several instances, the
class StringBuilder is used, most often in the manner that you're used
to seeing StringBuilder used. StringBuilder is a new Tiger class
intended to be a drop-in replacement for StringBuffer in cases where
thread safety isn't an issue.
1.6.1 How do I do that?
Replace all your StringBuffer code with StringBuilder code. Reallyit's as simple as that. If you're working in a single-thread environment, or in a piece of code where you aren't worried about multiple threads accessing the code, or synchronization, it's best to use StringBuilder instead of StringBuffer. All the methods you are used to seeing on StringBuffer exist for StringBuilder, so there shouldn't be any compilation problems doing a straight search and replace on your code. Example 1-5 is just such an example; I wrote it using StringBuffer, and then did a straight
search-and-replace, converting every occurrence of "StringBuffer" with
"StringBuilder".
Example 1-5. Replacing StringBuffer with StringBuilder
You'll see plenty of other code samples using StringBuilder in the rest
package com.oreilly.tiger.ch01;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class StringBuilderTester {
public static String appendItems(List list) {
StringBuilder b = new StringBuilder( );
for (Iterator i = list.iterator( ); i.hasNext( ); ) {
b.append(i.next( ))
.append(" ");
}
return b.toString( );
}
public static void main(String[] args) {
List list = new ArrayList( );
list.add("I");
list.add("play");
list.add("Bourgeois");
list.add("guitars");
list.add("and");
list.add("Huber");
list.add("banjos");
System.out.println(StringBuilderTester.appendItems(list));
}
}
of this book, so you'll be thoroughly comfortable with the class by book's
end.
1.6.2 What about...
...all the new formatting stuff in Tiger, like printf( ) and format( )? StringBuilder, as does StringBuffer, implements Appendable, making it usable by the new Formatter object described in Chapter 9. It really is a drop-in replacementI promise!