正如标题所暗示的那样,我正在寻找一种方法来将填充了x长度信息的数组添加到不断增长的数组列表中。
我已经完成了我的研究,似乎如果我选择将数组放入数组列表中,那么它将是列表中原始数组的单个值,其中我希望整个数组到数组列表。 / p>
我知道这很复杂,所以请参阅下文。
所以说我们经历了应用程序的第一个循环并生成以下数组
{1,2,3,4}
{5,6,7,8}
如果我将它放入Arraylist,它将是以下
1
2
3
4
5
6
7
8
然而我想要它如下
{1,2,3,4}
{5,6,7,8}
and so on...
原因是因为我想存储数组,以便我的程序在循环时测试存储的每个数组的值。
这在Java中可行吗?我确信它是,但我只是遗漏了一些东西!
答案 0 :(得分:3)
如果您知道预先生成的阵列数,则可以使用二维数组。
示例强>
int[] first = {1,2,3,4};
int[] second = {5,6,7,8};
int[][] all = new int[2][];
all[0] = first;
all[1] = second;
System.out.println(Arrays.deepToString(all));
<强>输出强>
[[1, 2, 3, 4], [5, 6, 7, 8]]
否则,只需使用ArrayList<int[]>
,但这很丑陋 - 请参阅下文。
示例强>
int[] first = {1,2,3,4};
int[] second = {5,6,7,8};
List<int[]> all = new ArrayList<int[]>();
all.add(first);
all.add(second);
// no nice String representation here as Arrays.toString not explicitly invoked
System.out.println(all);
<强>输出强>
[[I@466e466e, [I@46734673]
最终和最佳解决方案,使用ArrayList<ArrayList<Integer>>
。
示例强>
// cannot use primitive arrays in this context without tedious iteration
Integer[] first = {1,2,3,4};
Integer[] second = {5,6,7,8};
List<List<Integer>> all = new ArrayList<List<Integer>>();
all.add(Arrays.asList(first));
all.add(Arrays.asList(second));
System.out.println(all);
<强>输出强>
[[1, 2, 3, 4], [5, 6, 7, 8]]
最后的注释
您可能还想查看Map
API,看看Map<Object, List<Integer>>
甚至只是Map<Integer, Integer>
是否更符合您的数据要求。
答案 1 :(得分:0)
为什么不列出清单?将数组转换为列表很容易,然后你会得到:
List<List<Integer>> list = new ArrayList<List<Integer>>();
编辑:
让我们假设您有一个名为myArray
的数组。您添加到上面声明的列表如下:
list.add(Arrays.asList(myArray));
使用多个数组执行此操作,您将拥有一个包含多个单独列表的List,例如:
{1,2,3},{4,5,6},......等等