ForEachVariableIsElement
DRAFT

Misconception:

The variable in an enhanced for statement (also know as a for-each loop) corresponds to an element of the array or collection the loop iterates over. Thus one can assign to that variable to update the array or collection.

Incorrect

One can assign to the variable of an enhanced for statement to store a value in the corresponding array or collection element

Correct

The variable of an enhanced for statement contains a copy of the value of the corresponding array or collection element

Correction
Here is what's right.

At every iteration of an enhanced for statement the value of the corresponding array or collection element is copied into the loop’s variable.

Thus, in the first iteration of the following loop, the variable age is set to value of age[0], which means that the value 1 is copied into the age variable. In the next iteration, the value 2 is stored in the age variable, and so on.

int[] ages = new int[] {1, 2, 3};
for (int age : ages) { ... }

Thus, the variable age never represents the same memory location as an array element (age[0], age[1], and age[2]).

This means that the following loop does not set the elements of the sprites array:

Sprite[] sprites = new Sprite[10];
for (Sprite sprite : sprites) {
  sprite = new Sprite();
}

The same problem exists for arrays of primitive elements. The following loop does not affect the contents of the ages array:

int[] ages = new int[10];
for (int age : ages) {
  age = 19;
}

Behind the scenes of an enhanced for statement

The Java compiler desugars the enhanced for statement into a basic for statement like this:

int[] ages = new int[10];
for (int i=0; i<ages.length; i++) {
  int age = ages[i];
  age = 19;
}

As can be seen from this desugared code, the value 19 is assigned to a temporary variable, not to the array element.

The correct way to initialize such an array is to use a loop with an index:

int[] ages = new int[10];
for (int i=0; i<ages.length; i++) {
  ages[i] = 19;
}

Stay up-to-date

Follow us on  twitter to hear about new misconceptions.