Let’s go in pieces:
int[][] array
Here is declared an array of arrays of int
. It is an array in which each element is another array, which in turn contains integers.
int[][] array = new int[3][5];
Here I state that this array has 3 positions, and that each of these positions contains another array with 5 positions.
Worth remembering two things:
- the positions of an array start at zero (i.e.,
array[0]
is the first element, array[1]
is the second, etc).
- all elements are initialized with a value default. In the case of
int
, the value is zero
That is, an array with 3 positions has been created. Each of these positions is another array with 5 values int
, which in turn were initialized with the value 0
(zero).
To traverse the array, a for
traditional:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
In the first for
I go through the 3 elements of array
, using array.length
as stopping criterion (so I guarantee that the for
will not advance beyond array size).
As each of the elements of array
is another array, I do the second for
to travel it. But like all arrays int
have the same size (which in case is 5), was used the size of the first (array[0].length
) as a stop criterion. Even if I am in the second or third array, their size is equal to that of the first (always 5), and so the for
does not advance beyond the size of each array.
Why did they do that? I don’t know, maybe because it "worked", or because they thought "the size of all is the same, whatever to use". The problem is that this code trusts blindly in the fact that all arrays have the same size, which will not always be true:
// criar array com 3 posições, cada posição é outro array, mas ainda não defini os tamanhos
int[][] array = new int[3][];
array[0] = new int[20]; // primeiro array tem 20 elementos
array[1] = new int[3]; // segundo array tem 3 elementos
array[2] = new int[10]; // terceiro array tem 10 elementos
Now each array has a different size. If I always use the size of the first one (which is 20), it will give an error of ArrayIndexOutOfBoundsException
when trying to access the fourth element of the second array (since it only has 3 elements, but the second for
will try to access the fourth element as it is going up array[0].length
, which is 20).
In this case, the ideal is to use the size of the array you are traversing:
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
^ usar i em vez de 0
Just because the first code "worked" using array[0]
, doesn’t mean it’s the right thing to do.
"Why did you do it like that? I don’t know" All I know is I laughed when I read that part of the answer
– Jefferson Quesado