I know how to write arraylists
, but don't quite know how to write 2d arraylists
. Can you guys help me?
Asked
Active
Viewed 36 times
0

icravedeadmemes
- 9
- 3
-
Note that `arraylist` != `ArrayList`. – markspace Apr 06 '20 at 00:58
-
note that a 1D array can simulate a 2D array https://stackoverflow.com/questions/2151084/map-a-2d-array-onto-a-1d-array – Novaterata Apr 06 '20 at 01:03
-
Before anything else rad how to ask a question -> https://stackoverflow.com/help/how-to-ask – bichito Apr 06 '20 at 01:12
2 Answers
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);

Miłosz Tomkiel
- 125
- 8
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 Integer
s.

Chana
- 358
- 4
- 10