Java:添加到String的末尾

时间:2013-01-31 14:07:27

标签: java

我有一个String,如下所示

String result = ["A","B","C","D","E","F"]
List list = new ArrayList();

        list.add("One");
        list.add("One2");
        list.add("One3");

我有一个ArrayList,我想添加String结果,所以它应该看起来像

["A","B","C","D","E","F","One","One2","One3"]

我试过这种方式

String result = ["A","B","C","D","E","F"]
        for(int i=0;i<list.size();i++)
        {
        result = result+"list.get(i)"
        }

任何人都可以帮忙。

7 个答案:

答案 0 :(得分:2)

这是一种很好的方式,没有太多的走动

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

public class Tester4 {

    public static void main(String args[]) {

        String[] result = new String[] { "A", "B", "C", "D", "E", "F" };

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

        list.add("One");
        list.add("One2");
        list.add("One3");

        for(int i = result.length-1; i>= 0; i--) {

            list.add(0,result[i]);
        }

        for(String string : list) {
            System.out.println("Answer: " + string);
        }

    }

}

答案 1 :(得分:1)

正如@assylias指出的那样,你的问题似乎不清楚。假设您的变量“result”是一个字符串,请执行以下操作:

String result = "\"A\",\"B\",\"C\",\"D\",\"E\",\"F\"";
List list = new ArrayList();

list.add("One");
list.add("One2");
list.add("One3");

for(int i=0;i<list.size();i++)
{
   result += ",\"" + list.get(i) +"\""
}

那么“结果”的输出应为:

"A","B","C","D","E","F","One","One2","One3"

答案 2 :(得分:0)

["A","B","C","D","E","F"]不是字符串。试试这个......

String result = ""
for(int i = 0; i < list.size(); i++){
    result += list.get(i);
}

问候。

答案 3 :(得分:0)

您使用的变量“result”是一个String数组,而不是String。

如果你想要一个包含这些字符串的字符串列表,你应该写:

String[] result = {"A","B","C","D","E","F"};
ArrayList<String> list = new ArrayList<String>();
list.add("One");
list.add("One2");
list.add("One3");
for(int i=0;i<result.length;i++)
{
   list.add(i, result[i]);
}

因此,您将把数组的元素“result”放在列表之前。

答案 4 :(得分:0)

结果不是String,它是String []。所以,如果你想让结果看起来像

  

[ “A”, “B”, “C”, “d”, “E”, “F”, “一个”, “One2”, “One3”]

你需要在另一个String []中放入“One”,“Two”,“Three”,然后连接两个数组,例如它显示为 here :

答案 5 :(得分:0)

list.addAll(Arrays.asList(result)).toArray(new String[0]);

答案 6 :(得分:0)

Java中定义数组如下:String[] result = {"A","B","C"}

String[] result = {"A","B","C","D","E","F"};
List list = new ArrayList();

list.add("One");
list.add("One2");
list.add("One3");

List<String> newList = new ArrayList(Arrays.asList(result));
newList.addAll(list);

输出newList

[A, B, C, D, E, F, One, One2, One3]