| Author |
StringBuilder and String
|
Cory Max
Ranch Hand
Joined: Jul 20, 2005
Posts: 83
|
|
I understand the difference between the two but I have always used Strings in my code instead of StringBuilders. I am wondering how to set a stringbuilder object = a new string, not to append, not to insert, but to set it to a new string without the overhead of creating another object. for example, with strings I would have done: String s = ""; for (int i = 0 ; i < 10 ; i ++) { s = "" + i; System.out.println(s); } Append, appends the string, insert, inserts at a specified index. How do I clear the contents of my stringbuilder and set it equal to a new value? Thanks folks, Yeuker
|
There are only 10 types of people in this world... Those who understand binary and those who don't.
|
 |
Mark Dexter
Ranch Hand
Joined: Jun 03, 2007
Posts: 34
|
|
|
Since strings are immutable, you are creating a new String object with each iteration. So the StringBuilder will execute faster, since you are only creating one new object at the start of the loop instead a new object with each iteration. If you have "Thinking in Java", see page 506. Hope this helps. Mark Dexter
|
 |
Cory Max
Ranch Hand
Joined: Jul 20, 2005
Posts: 83
|
|
|
I understand what the differences are. I want to know how to clear the contents of the stringbuffer, then insert a new string.
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
|
Will the replace method do what you want ?
|
Joanne
|
 |
Cory Max
Ranch Hand
Joined: Jul 20, 2005
Posts: 83
|
|
Yup. Just what I needed. Just didnt look through the api as far as I should have:
|
 |
 |
|
|
subject: StringBuilder and String
|
|
|