Doubt using array

Asked

Viewed 110 times

2

I would like to know why the index is used in the code 0 when a for to identify if the size of the array is smaller than the counter j.

public class Aplicacao {

    public static void main(String[] args) {    
        int[][] array = new int[3][5];

        array[1][4] = 20;

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[0].length; j++) { // <-- aqui, por que array[0]?
                System.out.print(array[i][j] + "  ");
            }

            System.out.println();
        }
    }
}

2 answers

3

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.

  • 1

    "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

1

Hello.

// inicializacao da matriz
int[][] array = new int[3][5];

// inicializar a segunda linha, terceira coluna com o valor int 20
array[1][4] = 20;

For all the case, array[0] identifies the first line in the matrix, and in the initialization was used 3 as value, the matrix now has 3 lines, they are:

array[0]
array[1]
array[2]

Now, the sizes or number of columns for these 3 rows are the same, so use array[n-1].length (array[0].length, array[1].length, array[2].length) is the same.

System.out.println(array.length);
// saida: 3
System.out.println(array[0].length);
// saida: 5

Browser other questions tagged

You are not signed in. Login or sign up in order to post.