Thursday, December 11, 2008

How to empty a StringBuffer

We know that StringBuffer is reusable , We may want to empty a String Buffer ( lets say at end of a loop )
so how do you do it ?

The easiest way i came across use the method setLength()
public void setLength(int newLength)
You may have the case like
StringBuffer sb = new StringBuffer("HelloWorld")
// after many iterations and manipulations
sb.setlength(0);
// reuse sb

Please note you cant say
StringBuffer sb = "";
You will get a type mismatch error saying that "Cannot assign a value of type String to StringBuffer"
Makes sense as StringBuffer is not String , and they both inherit from java.lang.Object

4 comments:

  1. This is what I use

    StringBuffer sb = new StringBuffer();
    sb.delete(0, sb.length());

    ReplyDelete
  2. StringBuffer delete() does a System.arraycopy, setLength() just changes the point, so it is a better performance choice.

    ReplyDelete
  3. StringBuffer delete() does a

    System.arraycopy(value, start+len, value, start, count-end);

    The method setLength() is a better performance choice.

    ReplyDelete