3

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?

rubixibuc
  • 7,111
  • 18
  • 59
  • 98

5 Answers5

5

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
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
2

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
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

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.

Phynix
  • 46
  • 4
1

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.

Pavel
  • 4,912
  • 7
  • 49
  • 69
0

That is just the declaration, you need to initialize it. The 10 arrays would be null initially.

Sudhanshu Umalkar
  • 4,174
  • 1
  • 23
  • 33
  • Since Java isn't C, it will actually initialize all the slots to 0, or `null`, depending on if it's an `int` or reference type. – DaoWen Mar 20 '13 at 02:55
  • @DaoWen: No, it will initialize the slots to `null`, as `i` is an array of `int[]`. Each of *those* still needs to be created (and when they are, their slots will be initialized to `0`). – T.J. Crowder Mar 20 '13 at 02:56
  • @T.J.Crowder - You're right, in this case the empty `[]` on the end means there are no actual `ints` present to initialize to 0. I was editing my comment when you replied—thanks for pointing that out though. – DaoWen Mar 20 '13 at 02:59