I am defining an array like so: int [][] intervals = new int[10][10]; BUT my array will have to have different dimensions, depending on who calls the function in which this array is defined.
I wanted to try and do something like this: int [][] intervals = new int[][]; but it says “Variable must provide either dimension expressions or an array initializer”
I also tried int [][] intervals = null, but afterwards when i try and do intervals[3][4] = 10 it gives exception;
So how can i accomplish this?
Try to think of a multi-dimension array as an array of arrays
It’s not exactly like that inside the JVM, but that’s the best mental model to work with for these sorts of questions.
So, if you have
then your outer-array is null, and can later be initialised with
Which creates an array of
int[], but in that case each of the 10 inner-arrays are null.If you want them all to be the same size (e.g. an 10 x 5 array) then do something like:
But if you want them to be different sizes then do something like:
But all of these assume that you know how big you want your array to be before you start filling it.
If you don’t know that, then you want to use a
Listinstead – have a look atArrayList.Edit
I’ve just seen in your comment that this latter case is what you want, so …
Try something like:
Alternatively, you could have:
List< int[] >which would mean using a List for the outside collection, but an array for the inner collection, if you know how long your inner collection is going to be.List<Integer>[]which uses an array for the outer collection, and a list for the inner collection.It really depends on exactly how your code needs to work.