如何将arraylist转换为字符串? [英] how to convert arraylist into string?

查看:512
本文介绍了如何将arraylist转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者.在我的代码中,我有一个arraylist,我想完全输出为String.为此,我已经编写了这段代码.

I am beginner in java. In my code i have a arraylist and i want to output completely as a String. for this i have write this code.

package factorytest;

import java.util.ArrayList;
import java.util.List;

public class MatchingWord {

    public static void main(String[] args) {

        List <String> myList = new ArrayList<String>();
        myList.add("hello");
        myList.add("first");
        myList.add("second");
        myList.add("third");
        myList.add("fourth");

        // 1st approach
        String listString = "";

        for (String s : myList)
        {
            listString += s + "\t";
        }
System.out.println(listString);
    }

}

我的输出是

hello   first   second  third   fourth  

我不希望最后一个元素后面的最后一个\ t.我怎么能做到这一点.

i don't want the last \t after the last element. how can i achieve this.

推荐答案

一个解决方案不使用 for-each 循环,您可以执行以下操作:

One solution is not using for-each loop, you can do the following:

int i;
for(i = 0;i < myList.size() - 1;i++) {
    listString += myList.get(i) + "\t";
}
listString += myList.get(i);

我建议您使用 StringBuilder 代替+.

其他解决方案:

这篇关于如何将arraylist转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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