开发者

Getting (quickly) a String from an array of String [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Best way to convert an ArrayList to a string

I have an ArrayList in my class.

I need to make a String composed of all those Strings (I know, why not use a String in the first place - I'm dealing with amazing legacy code there and my hands are tied).

Is there a quickier way than something like :

String total;
for (String s : list)
{
   total += s;开发者_开发百科
}

Thank you for your help !


Yes, use a StringBuilder

StringBuilder sb = new StringBuilder();
for ( String st: list ) {
    sb.append(st);
}
String total = sb.toString();

This is not shorter code, but faster, as it prevents the massive amount of Object creation when using String concatenation (and thus in many cases lots of Garbage Collections).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜