Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I initialize a array/arraylist<int> of 2D array in Java?

Can I initialize ArrayList of 2D array, is this a thing?

So when I try to initialize this, below is my code

ArrayList<int>[][] suffle = new ArrayList<int>[row][col]; 

I get an error like this:

Error: Syntax error, insert "Dimensions" to complete ReferenceType

How can I fix this?

like image 465
Yiqing Rose Chen Avatar asked Mar 18 '23 08:03

Yiqing Rose Chen


1 Answers

It is a thing, but you have to use an object, not a primitive. This applies to all generic types.

ArrayList<Integer>[][] suffle = new ArrayList[row][col];

You're going to get some compiler warnings about the above declaration, but it is perfectly possible to do.

Depending on what it is you're doing, it might be better to use a list of lists, which will ensure type safety as oppose to the unchecked warning you'd get from the above...

List<List<Integer>> suffle = new ArrayList<>();

...or a standard two-dimensional array:

int[][] suffle = new int[row][col];
like image 120
Makoto Avatar answered Apr 02 '23 02:04

Makoto