对于Java中的每个循环

Anu*_*rag 3 java arrays foreach

我有一个示例代码,它创建一个大小为10的"数组",并尝试在For循环中使用反向值初始化它,例如:(9,8,7,6,5 ... 0):

int[] array = new int[10];
        for (int i = array.length - 1, j = 0; i >= 0; i--, j++) {
            System.out.println("Present value of i=" + i
                    + " Present value of j=" + j);
            array[j] = i;
            System.out.println("Array:" + j + "=" + i);
        }
        for (int k : array) {
            System.out.println(array[k]);
        }
Run Code Online (Sandbox Code Playgroud)

到现在为止还挺好.这是控制台的输出,非常完美:

Present value of i=9 Present value of j=0
Array:0=9
Present value of i=8 Present value of j=1
Array:1=8
Present value of i=7 Present value of j=2
Array:2=7
Present value of i=6 Present value of j=3
Array:3=6
Present value of i=5 Present value of j=4
Array:4=5
Present value of i=4 Present value of j=5
Array:5=4
Present value of i=3 Present value of j=6
Array:6=3
Present value of i=2 Present value of j=7
Array:7=2
Present value of i=1 Present value of j=8
Array:8=1
Present value of i=0 Present value of j=9
Array:9=0
Run Code Online (Sandbox Code Playgroud)

问题是For-each循环最后只是打印数组中的值:

for (int k : array) {
            System.out.println(array[k]);
        }
Run Code Online (Sandbox Code Playgroud)

打印数组的值为0,1,2 ... 9,其中应为9,8,7 ... 0

当我使用常规For循环打印数组时,它可以正常工作.我在这里错过了一些有趣的事吗?

rge*_*man 11

您已经从arrayforeach循环中获取了值,您将其再次用作数组中的索引,再次按顺序生成值.

打印一下k.更改

for (int k : array) {
    System.out.println(array[k]);
}
Run Code Online (Sandbox Code Playgroud)

for (int k : array) {
    System.out.println(k);
}
Run Code Online (Sandbox Code Playgroud)

输出结束:

9
8
7
6
5
4
3
2
1
0
Run Code Online (Sandbox Code Playgroud)


ajb*_*ajb 7

基本上,因为(int k : array)导致k遍历数组中的而不是索引,所以你所做的就等同于

System.out.println(array[array[0]]);
System.out.println(array[array[1]]);
System.out.println(array[array[2]]);
System.out.println(array[array[3]]);
...
System.out.println(array[array[9]]);
Run Code Online (Sandbox Code Playgroud)

这不是你想要的.