Java 如何将字符串数组添加到数组列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18264933/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:51:48  来源:igfitidea点击:

How to add string arrays to array list

javaarraysstringarraylist

提问by kjm

I'm trying to create an array list of arrays. When I'm done, I want the array list to look like this:

我正在尝试创建数组的数组列表。完成后,我希望数组列表如下所示:

[ [Mary] , [Martha,Maggie,Molly] ]

I'm trying to accomplish this by first defining "Mary" as a string array of length 1, and defining "Martha, Maggie, Molly" as a string array of length three. Then I attempt to add these arrays to an array list. But alas, the array list will not accept the arrays. Take a look:

我试图通过首先将“Mary”定义为长度为 1 的字符串数组,并将“Martha、Maggie、Molly”定义为长度为 3 的字符串数组来实现这一点。然后我尝试将这些数组添加到数组列表中。但遗憾的是,数组列表将不接受数组。看一看:

String[] s1 = new String[1];
String[] s3 = new String[3];

ArrayList<String[]> list1 = new ArrayList<String[]>();

s1[0]="Mary";
s3[0]="Martha";
s3[1]="Maggie";
s3[2]="Molly";

list1.add(s1[0]);
list1.add(s3[0]);
list1.add(s3[1]);
list1.add(s3[2]);

Any ideas on how I can add these arrays to list1, in order to form an array list of arrays?

关于如何将这些数组添加到 list1 以形成数组的数组列表的任何想法?

采纳答案by squiguy

You're adding the individual strings to the ArrayList instead of the String arrays that you created.

您将单个字符串添加到 ArrayList 而不是您创建的 String 数组。

Try just doing:

尝试只做:

list1.add(s1);
list1.add(s3);

回答by Josh M

They aren't being accepted because you are explicitly stating that your ArrayListis going to hold Stringarrays, and it appears you are passing in elements from Stringarrays as opposed to the entire array. Instead of adding an element from the array, try adding the entire array:

它们未被接受,因为您明确声明您ArrayList将保存String数组,并且您似乎是从String数组中传递元素而不是整个数组。不要添加数组中的元素,而是尝试添加整个数组:

list1.add(s1)

list1.add(s1)

回答by sanky jain

Try this. Create ArrayList of objects and then assin complete string.

尝试这个。创建对象的 ArrayList,然后插入完整的字符串。

ArrayList<Object> list = new ArrayList<Object>();       
    String s1[] = new String[1];
    String s3[] = new String[3];

    s1[0]="Mary";
    s3[0]="Martha";
    s3[1]="Maggie";
s3[2]="Molly";

list.add(s1);

回答by Julio Delgado

ArrayList<String> Jobs = new ArrayList<String>();    


String programmer = "programmer";
Jobs.add(programmer);


for(String AllJobs : Jobs){
    System.out.println(AllJobs);
}
}//array list //java code
//try this