-5

This might be a weird question but...

How can I use a List/ArrayList as type for a 2D Array?

In case I didn't explain myself properly:

int[][] arrayName = new int[9][9];

In this example I want to use ArrayList<int> instead of just int, but I'm not allowed to. Either that, or I'm probably using the wrong syntax.

Edit: Looks like I wasn't clear enough with my question (and wrote a misleading title, my bad, fixing it now).

What I have is a grid made with a 2D array like the example above, but I want an ArrayList of Integers as elements of the single cells of this grid.

ArrayList<Integer>[][] grid = new ArrayList<Integer>()[9][9]

Something like this. Is this the correct syntax? Am I even allowed to do it?

Whitesora
  • 1
  • 1

2 Answers2

0

As you can not use primitive type (int in your case) in collection you would need to use Interger wrapper

so the 2 dimension array list should be

List<List<Interger>> array = new ArrayList<List<Interger>>();
rahul shetty
  • 126
  • 7
0

Between <> need to be a class. In your case Integer

To make an 2D ArrayList you could do this:

ArrayList<ArrayList<Integer>> a = new ArrayList<ArrayList<Integer>>();

ArrayList<Integer> b = new ArrayList<Integer>();
b.add(1); b.add(2); b.add(3); b.add(4); b.add(5); b.add(6);

ArrayList<Integer> c = new ArrayList<Integer>();
c.add(3); c.add(7); c.add(1); c.add(3); c.add(9);

ArrayList<Integer> d = new ArrayList<Integer>();
d.add(8); d.add(3); d.add(3); d.add(8); d.add(3); d.add(6);

ArrayList<Integer> e = new ArrayList<Integer>();
e.add(7); e.add(2); e.add(8);

a.add(b); a.add(c); a.add(d); a.add(e);

for(ArrayList<Integer> aux : a) {

    for(Integer temp : aux) {

        System.out.print(temp + " ");

    }

    System.out.println("");

}

//1 2 3 4 5 6
//3 7 1 3 9 
//8 3 3 8 3 6 
//7 2 8 
KunLun
  • 3,109
  • 3
  • 18
  • 65