# 为什么“for each”中的左侧大小不等于右侧大小？

go评论73阅读模式

Why the left side size in for each is not equal to the right side?

# 问题

`for-each` 中声明的大小总是小于数组的大小。为什么？

``````int[][][] c = {{{1,2,3}}};
for(int [][] z : c )
//code
``````

c 是一个三维数组，所以 z 也应该是三维的，对吗？

``````int[][][] c = {{{1,2,3}}};
for (int[][][] z : c) // 这在语法上是错误的
//code
``````

The declared size in `for-each` is always less than the size of the array.why ?

``````int[][][] c = {{{1,2,3}}};
for(int [][] z : c )
//code
``````

c is a 3D array so should z, right?
like:

``````int[][][] c = {{{1,2,3}}};
for (int[][][] z : c) // which is syntactically wrong
//code
``````

The answer as I understand it from the comments and the below answer: the declaration inside `for-each`

in the 3D array `for-each` considers every 2D array as an element,

in the 2D array `for-each` considers every 1D array as an element and so on..

in the 1D array it takes the elements of the array directly as elements.

# 答案1

``````int[] arr = {1,2,3};
for (int i : arr) {
System.out.println(i);
}
``````

Read that construct as the `for-each` loop. In this case, for each `int[][]` in the `int[][][]`. Another example, `for-each` `int` in an `int[]`.

``````int[] arr = {1,2,3};
for (int i : arr) {
System.out.println(i);
}
``````

• 本文由 发表于 2020年10月7日 07:28:19
• 转载请务必保留本文链接：https://go.coder-hub.com/64235125.html
• arrays
• for-loop
• foreach
• java

go 71