Foreach with multidimensional arrays in Java

I read Java: full reference (9). In symbol 5: control expressions - section "Iterating over multidimensional arrays" Record:

The extended for version also works with multidimensional arrays. Remember, however, that in Java multidimensional arrays consist of arrays of arrays. (For example, a two-dimensional array is an array of one-dimensional arrays.) This is important when iterating over a multi-dimensional array, since each iteration receives the next array, rather than a separate element. In addition, the iteration variable in for loop must be compatible with the type of the resulting array. For example, in the case of a two-dimensional array, the iteration of the variable should be a reference to a one-dimensional array. In general, when using for-each to iterate over an array of N dimensions, the resulting objects will be arrays of sizes N-1. To understand the consequences of this, consider the following program. It uses nested loops to get the elements of a two-dimensional array into a row-order, from the first to the last.

I cannot understand why "iterate over an array of N dimensions, the resulting objects will be arrays of N-1 dimensions." It's true?

+5
source share
4 answers

An array of N dimensions is indeed an array of (N-1) -dimensional arrays. Therefore, when we iterate over an array of N dimensions, we iterate over all its constituent (N-1) -dimensional arrays, as indicated.

For example, consider a two-dimensional array:

int[][] array = {{1,2,3}, {4,5,6}}; 

This is really an array of one-dimensional arrays: {1,2,3} and {4,5,6} .

+8
source

Think of your multidimensional array as (x, y, z). When you iterate over the first coordinate, you fix x (x = 1, 2, ..., n) and get a (y, z) 2d array.

Then you fix y (y = 1, 2, ..., m) and get a (z) 1d array.

+1
source

Consider a three-dimensional matrix (mathematically defined).

When you iterate through the rows, you get two-dimensional matrices, and when you iterate over each of the two-dimensional matrices, you get one-dimensional vectors.

  // Three dimensions String[][][] stringArray = new String[3][3][3]; // Iterating over one dimension // results in two dimensional array for (String[][] strings : stringArray) { // Iterating over one dimension // results in one dimensional array for (String[] strings2 : strings) { // Iterating over one dimension for (String string : strings2) { } } } 
+1
source

When you iterate over an array, you β€œset” one dimension and leave the rest undefined. Therefore, when you have a dimensional array N, when you enter a loop, you use an array of dimensions N-1 (inside the for-each loop).

0
source

Source: https://habr.com/ru/post/1214176/


All Articles