What`s New in Java 1.5 Tiger? - Adding StringBuilder to the Mix
(Page 6 of 6 )
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 StringBuffer 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.
How do I do that?
Replace all your StringBuffer code with StringBuilder code. Really—it’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
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));
}
}
You’ll see plenty of other code samples using StringBuilder in the rest of this book, so you’ll be thoroughly comfortable with the class by book’s end.
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 replacement—I promise!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article was taken from chapter one of Java 1.5 Tiger: A Developer's Notebook, written by Brett McLaughlin and David Flanagan (O'Reilly, 2004; ISBN: 0596007388). Check it out at your favorite bookstore. Buy this book now.
|
|