连接String对象列表的最佳方法是什么? [英] Best way to concatenate List of String objects?

查看:159
本文介绍了连接String对象列表的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

连接String对象列表的最佳方法是什么?我想这样做:

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);
}

我发现这比使用StringBuilder / StringBuffer方法更整洁。

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

任何想法/评论?

推荐答案

你的方法依赖于Java的ArrayList#toString()实现。

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

虽然Java API中记录了实现并且不太可能发生变化,但它有可能实现。自己实现它(循环,StringBuilders,递归,无论你更喜欢什么)都更可靠。

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.

这篇关于连接String对象列表的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆