If you look at what happens to arr
in the first loop, it becomes obvious.
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);
}
This prints:
i = 1
arr = [1, 0, 3, 4]
i = 0
arr = [0, 0, 3, 4]
i = 3
arr = [0, 0, 3, 0]
i = 0
arr = [0, 0, 3, 0]
0
0
3
0
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);
}
To be able to index the array, you need to use the traditional for loop, like this:
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);
}