6

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?

Roman C
  • 49,761
  • 33
  • 66
  • 176
user2458768
  • 115
  • 4
  • 4
  • 12

2 Answers2

8

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • it works but how to show this ? Iterator it = ArrayList.iterator(); while(it.hasNext()) { Integer a = it.next(); System.out.println(a); } – user2458768 Nov 09 '13 at 18:30
  • @user2458768 Take a look at the code that prints the array (look at the updated demo to see it run on ideone). – Sergey Kalinichenko Nov 09 '13 at 18:37
  • 1
    This is so counterintuitive and unreadable... Not criticizing you of course, criticizing Java. – shinzou Aug 03 '16 at 19:57
  • Important Note: If you want to edit, lets say add an element to the `4, 5, 6` array using `group.get(1).add(999)`, it would not allow you to do so. This is because `Arrays.asList` will return an `AbstractList` instead of `ArrayList`. (Wrap it inside the constructor like `ArrayList<>(Arrays.asList(4, 5, 6))` if you need to edit the lists. https://ideone.com/0WEVZ4 – kaushalpranav Nov 26 '22 at 10:55
1

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));
Roman C
  • 49,761
  • 33
  • 66
  • 176