Reputation: 7417
In Java you can do this
int[][] i = new int[10][];
Does this just create 10 empty arrays of int? Does it have other implications?
Upvotes: 3
Views: 2802
Reputation: 425238
Executing your code creates an array of size 10, each element of which can hold a reference to a int[]
, but which are all initialized to null.
In order to use the int[]s, you would have to create new int[] for each of the element, something like this:
for (int n = 0; n < 10; n++)
i[n] = new int[10]; // make them as large as you need
Upvotes: 2
Reputation: 5162
Here you create ten new int[0]
arrays. You have to manually initialize it, it's useful when you don't need square matrix:
int[][] array = new int[10][];
for (int i = 0; i < array.length; i++) {
array[i] = new int[i];
}
If you need square matrix you can do:
int[][] array = new int[10][10];
And it will be initialized with default values.
Upvotes: 1
Reputation: 46
Yes, it does; however, each of those arrays are null. You have to then initialize each of those sub-arrays, by saying int[10][0] = new int[MY_SIZE], or something similar. You can have arrays with different lengths inside the main array; for example, this code would work:
int[][] i = new int[10][];
for(int ind = 0; ind<10;ind++){
i[ind]=new int[ind];
}
It is just an array of arrays.
Upvotes: 1
Reputation: 4202
That is just the declaration, you need to initialize it. The 10 arrays would be null initially.
Upvotes: 0
Reputation: 1075159
It creates a 10-entry array of int[]
. Each of those 10 array references will initially be null
. You'd then need to create them (and because Java doesn't have true multidimensional arrays, each of those 10 int[]
entries can be of any length).
So for instance:
int i[][] = new int [10][];
i[0] = new int[42];
i[1] = new int[17];
// ...and so on
Upvotes: 5