java - 在 Java 中使用多维数组的 Foreach

标签 java

我读了 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/

相关文章:

java - 返回值赋值问题(对于原始数据类型)

java - JTOpen 用户空间读取

java - 连接到服务器时客户端窗口不会关闭

java - 多个词不被搜索,不占用空间

java - Android:Resources.getSystem().getIdentifier 返回 java.lang.IllegalArgumentException

java - 使用超出范围的文字进行计算

java - 如何在 Android 中使用 Volley 发送 Post 请求?

java - 将数据插入到java JDBC中的很多列中

JavaMail 异常 javax.mail.AuthenticationFailedException 534-5.7.9 需要特定于应用程序的密码

Java 小程序 : Nested Loops color change