开发者

equivalent of + in StringBuffer

I have been using String to do the following.

String x = "a";
String y = "b";
String z = y+""+x;
x = y;
y = z;

So the final values of x and y are b and 开发者_运维百科ba. I tried to use StringBuffer.

StringBuffer x = new StringBuffer("a");
StringBuffer y = new StringBuffer("b");
StringBuffer z = new StringBuffer();
z = y+""+x;   //??? 

API provides append function but it doesn't do what concatenation does. Is there a equivalent for concatenation in StringBuffer class?


Dont' use StringBuffer unless you have to. Java 5.0 and later uses StringBuilder by default

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

StringBuilder x = new StringBuilder("a");
StringBuilder y = new StringBuilder("b");
StringBuilder z = new StringBuilder().append(x).append(y);


The method you want is append: z = x.append(" ").append(y);

As you can see, the appends can be cascaded for a nice code flow.

But better still will be to use a StringBuilder if you are on Java 1.5 or higher. StringBuffer is a synchronized class that is good when you need thread-safe code. When your variable does not need thread safety, use StringBuilder instead to get better performance.


You can use StringBuffer.append(StringBuffer):

z.append(y).append(x);


String z = y.toString() + x.toString();

or

StringBuilder z = new StringBuilder();
z.append(y).append(x);

Notes:

  1. The + "" + is superfluous so I've removed it.
  2. Unless you intend to share the string buffer across threads, you should be using StringBuilder instead of StringBuffer.


No there is not; The + operator used on String is a special case for objects in Java. Only String can use it. To do concatenation in StringBuffer, its more roundabout. You would have to use append() (or god forbid, convert them to String, use +, and then convert the result back to StringBuffer).

With StringBuffer, you can append another StringBuffer. ie:

 stringBuffer1.append(stringBuffer2)


StringBuffer does not natively support + like String does. You have to use the append methods.


AHHH

Strings are immutable, so every time you do a z + x you are actually instantiating a whole new object containing the concatenation of the first two.

StringBuffers are mutable, which means they can be changed without creating new instances. This allows one stringbuffer to be created, and appended with additional string values as needed.

StringBuffer a = new StringBuffer("a");
a.append("b").append("c");
a.append("d");

will result in "abcd" when a.toString() is called.


Assuming that you want:

  • x has a value of "a"
  • y has a value of "b"
  • z has a value of "ab"

Then, no, StringBuffer/Builder won't do that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜