Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java initialize 2d arraylist

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?

like image 605
user2458768 Avatar asked Nov 09 '13 17:11

user2458768


2 Answers

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.

like image 55
Sergey Kalinichenko Avatar answered Oct 13 '22 10:10

Sergey Kalinichenko


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));
like image 25
Roman C Avatar answered Oct 13 '22 12:10

Roman C