Reputation: 21
int[] a = {1, 2, 3,4,1};
for (int n: a) {
a[n] = 0;
}
for (int n: a) {
System.out.print(n);
}
This for each loop showing something unexpected result when I make a all array elements 0.Instead of showing all '0' it is giving output something like '00301'.Not able to understand how this is working?
Upvotes: 0
Views: 85
Reputation: 159106
If you print out what it does, you'll see for yourself:
int[] a = {1, 2, 3,4,1};
System.out.println(Arrays.toString(a));
for (int n: a) {
System.out.print("a[" + n + "] = 0; -> ");
a[n] = 0;
System.out.println(Arrays.toString(a));
}
Output
[1, 2, 3, 4, 1]
a[1] = 0; -> [1, 0, 3, 4, 1]
a[0] = 0; -> [0, 0, 3, 4, 1]
a[3] = 0; -> [0, 0, 3, 0, 1]
a[0] = 0; -> [0, 0, 3, 0, 1]
a[1] = 0; -> [0, 0, 3, 0, 1]
Upvotes: 0
Reputation: 21
As stated by the Oracle documentation, the java for-each loop hides the iterator, and gives you access to only the values in the iterable (array). Therefore, the for-each loop should not be used for mainupulating the original array, rather should be used for working with the data of the array. https://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html If you want to manipulate the original array, your best bet is to use the conventional for loop.
Upvotes: 2
Reputation: 7325
In:
for (int n: a)
n
is the value of a particular index the array, not the index itself. So, you are basically setting 0 at index 1, 2, 3,4,1. Luckily there is no value greater than 4 (the length of the array) or negative number else you will get ArrayIndexOutOfBoundException.
for (int i=0; i<a.length;i++){
a[i] = 0;
}
Use the above code and you will get the expected output.
Upvotes: 1
Reputation: 201447
It's two for-each loops over the contents of an int[]
.
Loop 1: for each n
in 1, 2, 3, 4, 1
set the contents of the array to zero for indices 1, 0, 3, 0 and 1. Which you can see by changing it to
for (int n: a) {
System.out.println(n);
a[n] = 0;
}
Leaving the contents of a
as 0, 0, 3, 0, 1
then
Loop 2: for each n
in 0, 0, 3, 0, 1
print n
.
Thus your program prints 00301.
Upvotes: 1
Reputation: 29266
a[n] = 0;
is setting the a[some_value_from_the_array]
to 0, not setting all the array elements to 0.
Upvotes: 2