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 !

2
  • Probably is ; didn't see this one when I searched. Thanks a lot. Commented Apr 1, 2011 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. Commented Apr 1, 2011 at 15:59

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

The problem in the variant in the question is more the repeated copying of the internal char[] than the creating of new String objects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.