Java初始化二维数组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19880185/
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
Java initialize 2d arraylist
提问by user2458768
I want to do 2D dynamic ArrayList example:
我想做二维动态 ArrayList 示例:
[1][2][3]
[4][5][6]
[7][8][9]
and i used this code:
我使用了这个代码:
ArrayList<ArrayList<Integer>> group = new ArrayList<ArrayList<Integer>>();
group.add(new ArrayList<Integer>(1, 2, 3));
how should i initialize this arraylist?
我应该如何初始化这个数组列表?
采纳答案by dasblinkenlight
If it is not necessary for the inner lists to be specifically ArrayList
s, one way of doing such initialization in Java 7 would be as follows:
如果内部列表不需要专门为ArrayList
s,则在 Java 7 中进行此类初始化的一种方法如下:
ArrayList<List<Integer>> group = new ArrayList<List<Integer>>();
group.add(Arrays.asList(1, 2, 3));
group.add(Arrays.asList(4, 5, 6));
group.add(Arrays.asList(7, 8, 9));
for (List<Integer> list : group) {
for (Integer i : list) {
System.out.print(i+" ");
}
System.out.println();
}
回答by Roman C
Use
用
group.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3)));
The ArrayList
has a Collection
parameter in the constructor.
该ArrayList
有一个Collection
在构造函数中的参数。
If you define the group
as
如果你定义group
为
List<List<Integer>> group = new ArrayList<>();
group.add(Arrays.asList(1, 2, 3));