Consider this code:
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);
}
}
}
It prints:
0
0
3
0
What’s this? For-each is supposed to run over all the elements in the array, why would it run arr[3]=0 but not arr[2]=0?
If you look at what happens to
arrin the first loop, it becomes obvious.This prints:
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:
To be able to index the array, you need to use the traditional for loop, like this: