Reputation: 73
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?
Upvotes: 4
Views: 8346
Reputation: 1375
Wherever you need to use generic types within diamond brackets, you should not use primitive types such as int, double etc. Rather, respective wrapper types such as Integer and Double etc should be used.
After I saw this question being asked in many forums, I have explained this with examples on my blog as well - http://www.javabrahman.com/corejava/how-to-resolve-syntax-error-insert-dimensions-to-complete-referencetype/
(Note/Disclosure - the above link is from a blog owned by me)
Upvotes: 0
Reputation: 106430
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];
Upvotes: 5
Reputation: 5755
Yes, you can make a 2-dimensional array of Object types (in this case ArrayList).
But you need to write it as:
ArrayList<Integer>[][] suffle = new ArrayList[row][col];
Also make sure you initialize row and col as integer values, before you initialize the array list.
The individual elements of suffle will be declared as ArrayList types, but not initialized. You'll need to individually initialize them.
Upvotes: 0
Reputation: 57294
You can also stick entirely with primitives, i.e.
int[][] i = new int[row][col];
Or mix and match a list of int[]
ArrayList<int[]> al = new ArrayList<>();
And almost an array of lists:
/* writing new ArrayList<Integer>[1], which is what
you'd want to do, is not allowed for array creation.*/
ArrayList<Integer>[] a = new ArrayList[1];
Upvotes: 2