Java initialize 2d arraylist

前端 未结 2 1708
野趣味
野趣味 2021-02-06 15:03

I want to do 2D dynamic ArrayList example:

[1][2][3]
[4][5][6]
[7][8][9]

and i used this code:

 ArrayList

        
相关标签:
2条回答
  • 2021-02-06 15:31

    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.

    0 讨论(0)
  • 2021-02-06 15:32

    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));
    
    0 讨论(0)
提交回复
热议问题