Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

What is the best way to concatenate a list of String objects? I am thinking of doing this way:

List<String> sList = new ArrayList<String>();

// add elements

if (sList != null)

{

    String listString = sList.toString();

    listString = listString.subString(1, listString.length() - 1);

}

I somehow found this to be neater than using the StringBuilder/StringBuffer approach.

Any thoughts/comments?

1 Answer

0 votes
by (46k points)

Your approach is dependent on Java's ArrayList#toString() implementation.

While the implementation is documented in the Java API and very unlikely to change, there's a chance it could. It's far more reliable to implement this yourself (loops, StringBuilders, recursion whatever you like better).

Sure this approach may seem "neater" or more "too sweet" or "money" but it is, in my opinion, a worse approach.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...