-
Step 1
On your screen An enhanced for loop over an int array with each value read in turn.
int[] lanes = {3, 7, 2, 9};
for (int lane : lanes)
{
addObject(new Coin(), lane, 0);
}
Same form as 4.6. Read the colon as "in": for each int lane in lanes.
No index, no length, no condition. Nothing to get off by one.
When you only need the VALUES, this is the better loop.
-
Step 2
On your screen An attempt to assign to the loop variable, with the array unchanged afterward.
// Does NOT change the array.
for (int lane : lanes)
{
lane = lane * 2;
}
// lanes is still {3, 7, 2, 9}
This is the limitation, and it is worth meeting deliberately because it fails in silence.
`lane` is a COPY of the value, not the slot. Doubling the copy changes the copy. The array is untouched, there is no error, and nothing tells you.
To write into the array you need the index:
`for (int i = 0; i < lanes.length; i++) { lanes[i] = lanes[i] * 2; }`
-
Step 3
On your screen A decision table for choosing between the two loop forms.
The choice, in one line each:
Reading values only: enhanced for. Shorter and safer.
Need the position: index loop.
Need to WRITE into the array: index loop.
Unit 6 uses index loops almost exclusively, because a tile map is entirely about position.