0

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 !

Community
  • 1
  • 1
Raveline
  • 2,660
  • 1
  • 24
  • 28
  • Probably is ; didn't see this one when I searched. Thanks a lot. – Raveline Apr 01 '11 at 15:53
  • 1
    Note that that question is pretty old - I've just added an answer there myself pointing to a rather newer library. There's certainly no need to code this yourself. – Jon Skeet Apr 01 '11 at 15:59

1 Answers1

5

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).

Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119
  • The problem in the variant in the question is more the repeated copying of the internal `char[]` than the creating of new `String` objects. – Paŭlo Ebermann Apr 01 '11 at 16:28