gpt4 book ai didi

java - java 的 for-each 行为不一致

转载 作者:行者123 更新时间:2023-12-01 06:26:01 24 4
gpt4 key购买 nike

考虑这段代码:

class Jm44 {

public static void main(String args[]){

int []arr = {1,2,3,4};
for ( int i : arr )
{
arr[i] = 0;
}

for ( int i : arr )
{
System.out.println(i);
}


}

}

它打印:

0 
0
3
0

这是什么? for-each 应该运行数组中的所有元素,为什么它会运行 arr[3]=0但不是arr[2]=0

最佳答案

如果你看看第一个循环中 arr 发生了什么,它就变得很明显了。

    int[] arr = {1, 2, 3, 4};
for (int i : arr) {
System.out.println("i = " + i);
arr[i] = 0;
System.out.println("arr = " + Arrays.toString(arr));
}

for (int i : arr) {
System.out.println(i);
}

打印:

i = 1arr = [1, 0, 3, 4]i = 0arr = [0, 0, 3, 4]i = 3arr = [0, 0, 3, 0]i = 0arr = [0, 0, 3, 0]0030

You are modifying the values in the array, using the values in the array as indexes. The "foreach" loop goes through the values of the array, not the indexes of the array. After removing the syntactic sugar, here is what your foreach loop actually is:

    int[] arr = {1, 2, 3, 4};
for (int index = 0; index < arr.length; index++) {
int i = arr[index];
arr[i] = 0;
}

for (int i : arr) {
System.out.println(i);
}

为了能够索引数组,您需要使用传统的 for 循环,如下所示:

    int[] arr = {1, 2, 3, 4};
for (int i = 0; i < arr.length; i++) {
arr[i] = 0;
}

for (int i : arr) {
System.out.println(i);
}

关于java - java 的 for-each 行为不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1174028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com