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

I have 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 expect to get:

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

but instead i get

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

Just ... why?

Regards, Jellyfish

+6
source share
3 answers

Because " i " is a copy of an array element, not a reference to it :) You are changing a local variable, not an array element

this code is equivalent

 for(int index = 0; index < array.length; index++) { int i = array[index]; ... } 
+19
source

It's simple. If you write

 int i = positions[0]; 

Then you copy positions[0] by value, not by reference. You cannot change the original value in positions[0] of i . The same goes for assignment i inside the foreach loop.

The solution does not have a foreach loop

 for (int i = 0; i < positions.length; i++) { if (positions[i] <= 0) positions[i] = -1; } 
+2
source

This happens behind the scenes if we use the extended 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 inner loop variable. See what happens: you assign a new value to i , but i loaded with the next element in the array in the next iteration.

So, practically speaking, we cannot use the variable declared in the extended loop to modify the underlying array.

Link: JLS 3.0, 14.14.2

+2
source

Source: https://habr.com/ru/post/888413/


All Articles