Java: Foreach loop not working as expected on int array?

34,393

Solution 1

Because "i" is a copy of an array element and not a reference to it :) You modify a local variable, not an array's element

this code is equivalent to

for(int index = 0; index < array.length; index++) {

int i = array[index];
...
}

Solution 2

This happens behind the scenes if we use the enhanced for loop with arrays:

int[] array = {1,2,3,4,5};
for($i = 0; $i<array.length; $i++) {
  int i = array[$i];
  // your statements
  if (i <= 0) i = -1;
}

$i is just a placeholder for an unnamed internal loop variable. See what happens: you assign a new value to i but i is loaded with the next array item in the next iteration.

So, practically spoken, we can't use the variable declared in the enhanced for loop to modify the underlying array.

Reference: JLS 3.0, 14.14.2

Solution 3

It's simple. If you write

int i = positions[0];

Then you copy positions[0] by value, not by reference. You cannot modify the original value in positions[0] from i. The same applies to assigning i within a foreach loop.

The solution is without a foreach loop

for (int i = 0; i < positions.length; i++)
{
    if (positions[i] <= 0) positions[i] = -1;
}
Share:
34,393
jellyfish
Author by

jellyfish

Far, far away from my 10.000 hours, but I'm always willing to learn! :-) Atm working with Google Android.

Updated on June 11, 2020

Comments

  • jellyfish
    jellyfish almost 4 years

    I've got a pretty simple loop:

    int[] positions = {1, 0, 0}
    
    //print content of positions
    
    for (int i : positions)
    {
        if (i <= 0) i = -1;
    }
    
    //print content of positions
    

    Now, what I would expect to get is:

    array: 1, 0, 0
    array: 1, -1, -1
    

    but instead I get

    array: 1, 0, 0
    array: 1, 0, 0
    

    Just... why?

    Kind regards, jellyfish

  • Aleksandrus
    Aleksandrus almost 9 years
    it took me a long time to find this answer... i have an array and was instantiating objects inside foreach, and accessing them later with index, and i got null pointer exception. so for and foreach are NOT the same...