0

I know how to write arraylists, but don't quite know how to write 2d arraylists. Can you guys help me?

2 Answers2

1

SomeObject[] is array and SomeObject[][] is 2D array. Below you can see example integer 2D array.

int[][] array2d = new int[][] {
  {1,2,3},
  {4,5,6},
  {7,8,9}
};

array2d[1][1] == 5; // this is true

There are no 2D ArrayLists, you can fake it by making normal array of ArrayLists or ArrayList containing multiple ArrayLists.

// Array of ArrayLists
ArrayList[] arr = new ArrayList[arraysize];

// ArrayList containing another ArrayList
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
a.add(b);
1

2D arrays in Java are essentially arrays consisting of arrays. Each element in the array is itself an array.

int[][] arr = {
    new int[] = { 1, 2, 3 },
    new int[] = { 4, 5, 6 },
    new int[] = { 7, 8, 9 }
}

The same can be created with ArrayLists.

ArrayList arrList = new ArrayList<ArrayList<Integer>>();
arrList.add(new ArrayList<Integer>(Arrays.asList(1, 2, 3)));
arrList.add(new ArrayList<Integer>(Arrays.asList(4, 5, 6)));
arrList.add(new ArrayList<Integer>(Arrays.asList(7, 8, 9)));

The data type of the parent ArrayList is <ArrayList<Integer>>. Each element in the parent arrList is itself of type ArrayList which contains Integers.

Chana
  • 358
  • 4
  • 10