Reputation: 1655
Just two questions in regards to this code.
package experimental;
import java.sql.Array;
public class foreachExp {
public int[] anArray = {1, 2, 3, 4, 5,};
public void foreachArray() {
for (int i : anArray) {
anArray[i] = i + 1;
}
}
}
Upvotes: 0
Views: 11744
Reputation: 11483
for-each does not work based on array index but implements an iterative solution, the int i
variable will be representative of a single element of data from your supplied array. So in the loop, you effectively call:
anArray[1] = 1 + 1;
anArray[2] = 2 + 1;
anArray[3] = 3 + 1;
anArray[4] = 4 + 1;
anArray[5] = 5 + 1;
As you can see, anArray[5]
would be out of bounds, as the length of the array is only 5 long (0-4)
If you want to change the values, you do not use a for-each loop (could hackily do it using a Box
of some sort, but with an array it would be silly to).
So with an array, this would be the advisable solution:
for (int i = 0; i < anArray.length; i++) {
anArray[i]++;
}
As you have already mentioned
Upvotes: 6
Reputation: 106508
The fundamental difference between a for
loop and an enhanced-for loop is that the enhanced-for loop actually binds the values of the array to the variable itself.
So, your enhanced-for is pulling this on each iteration:
Enhanced for loops aren't meant for changing values. You would use a normal for
loop for that.
Upvotes: 2
Reputation: 1182
When you write
for (int i : anArray) {
i
refers to the value itself, not the index. So asking for array[5]
gives you an out of bounds exception (valid indices are 0 to 4).
You can instead use a normal for loop:
for (int i=0; i<anArray.length; ++i) {
anArray[i]++;
}
Upvotes: 3