我读了 Java:完整引用(第 9 期)。在字符 5:控制语句 - 迭代多维数组部分 写:
The enhanced version of the for also works on 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 multidimensional array, because each iteration obtains the next array, not an individual element. Furthermore, the iteration variable in the for loop must be compatible with the type of array being obtained. For example, in the case of a two-dimensional array, the iteration variable must be a reference to a one-dimensional array. In general, when using the for-each for to iterate over an array of N dimensions, the objects obtained will be arrays of N–1 dimensions. To understand the implications of this, consider the following program. It uses nested for loops to obtain the elements of a two-dimensional array in row- order, from first to last.
我不明白为什么“要遍历 N 维数组, 得到的对象将是N-1维的数组。是吗?
最佳答案
N 维数组实际上是一个 (N-1) 维数组。因此,当我们遍历一个 N 维数组时,我们就是在遍历其所有构成的 (N-1) 维数组,如图所示。
例如,考虑一个二维数组:
int[][] array = {{1,2,3}, {4,5,6}};
这实际上是一维数组的数组:{1,2,3}
和 {4,5,6}
。
关于java - 在 Java 中使用多维数组的 Foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28722209/