我正在尝试创建一个在每个索引处都有字符串数组的Arraylist。我使用了以下代码:
ArrayList<String[]> deliveryTimes = new ArrayList<String[]>();
String[] str = new String[times.size()];//times is an Arraylist of string
for(int i=0; i<times.size();i++){
str[i] = times.get(i);
}
deliveryTimes.add(str);
使用上面的代码,str数组的所有元素都在deliveryTimes arraylist中的不同索引处添加。但我想在索引处添加str作为数组。所以它应该如下:
[["a","b","c"],["aa","bb","cc"],["aaa","bbb","ccc"]]
但它就像:
["a","b","c","aa","bb","cc","aaa","bbb","ccc"]
答案 0 :(得分:2)
....
String[] first = new String[]{"a", "b", "c"};
String[] second = new String[]{"aa", "bb", "cc"};
String[] third = new String[]{"aaa", "bbb", "ccc"};
addArrays(first, second, third);
...
ArrayList<ArrayList<String>> addArrays(String[]... strings) {
ArrayList<ArrayList<String>> allTimes = new ArrayList<>(strings.length);
for (String[] array : strings) {
allTimes.add(new ArrayList<>(Arrays.asList(array)));
}
return allTimes;
}
allTimes包含:[[a,b,c],[aa,bb,cc],[aaa,bbb,ccc]]
答案 1 :(得分:0)
您的deliveryTimes
列表只包含一个String[]
。将多个String[]
添加到deliveryTimes
列表。
ArrayList<String[]> deliveryTimes = new ArrayList<String[]>();
String[] one = new String[]{"a", "b", "c"};
String[] two = new String[]{"aa", "bb", "cc"};
String[] three = new String[]{"aaa", "bbb", "ccc"};
deliveryTimes.add(one);
deliveryTimes.add(two);
deliveryTimes.add(three);
for (String[] str : deliveryTimes) {
System.out.println(Arrays.toString(str));
}
<强>输出强>
[a,b,c]
[aa,bb,cc]
[aaa,bbb,ccc]
您需要拆分时间列表并将它们分别添加到deliveryTimes列表。