質問

What is the difference between String class and StringBuffer class?

役に立ちましたか?

解決

Strings are immutable. Their internal state cannot change. A StringBuffer allows you to slowly add to the object without creating a new String at every concatenation.

Its good practice to use the StringBUilder instead of the older StringBuffer.


A common place to use a StringBuilder or StringBuffer is in the toString method of a complicated object. Lets say you want the toString method to list elements in an internal array.

The naive method:

String list = ""; 
for (String element : array) {
    if (list.length > 0) 
        list += ", ";
    list += element;
}

return list;

This method will work, but every time you use a += you are creating a new String object. That's undesirable. A better way to handle this would be to employ a StringBuilder or StringBuffer.

StringBuffer list = new StringBuffer(); 
for (String element : array) {
    if (list.length() > 0) 
        list.append(", ");
    list.append(element);
}

return list.toString();

This way, you only create the one StringBuffer but can produce the same result.

他のヒント

"String: http://docs.oracle.com/javase/tutorial/i18n/text/characterClass.html

String buffer: http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html

Job done. Google is your friend

When you say string bufefer, you shoudl probably look into stringbuilder instead.

You can append to them to make 'new' strings.

StringBuilder sb = new StringBuilder
sb.append("stuff here").append("more stuff here").append.....

A string is just a string and can't be changed.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top