Java initialize 2d arraylist

大憨熊 提交于 2020-11-30 14:58:21

问题


I want to do 2D dynamic ArrayList example:

[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?


回答1:


If it is not necessary for the inner lists to be specifically ArrayLists, one way of doing such initialization in Java 7 would be as follows:

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();
}

Demo on ideone.




回答2:


Use

group.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3)));

The ArrayList has a Collection parameter in the constructor.

If you define the group as

List<List<Integer>> group = new ArrayList<>();
group.add(Arrays.asList(1, 2, 3));


来源:https://stackoverflow.com/questions/19880185/java-initialize-2d-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!