如果事先知道产生的数组个数,就可以使用二维数组。
示例
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> 是否更适合您的数据需求。