There is an instance field:

private int[] arr = new int[42]; 

I use the code:

 for (int cell : arr) { cell = -1; } 

I hoped that this code would fill the array with -1 elements. This did not happen. The array is still zeros.

Please explain why this happened. What code is the foreach loop equivalent in this case?

  • 3
    in foreach, the iterative variable is read only. Examples - UserName
  • one
    @UserName Of course you are wrong, a person adds -1 to it and the code compiles, how can it be read-only? If objects were stored in the array, and not primitives, then their state could be changed. - Igor Fedorov
  • @IgorFedorov I tried with Integer. Anyway, you cannot change the array with for-each. - iramm
  • one
    @iramm because the objects of the Integer class are not mutable, you can take some class like class Test {int x;}, and change the x values ​​in foreach, then the changes will be displayed in the array. - Igor Fedorov
  • one
    Schild probably wrote a little different, and what happened was the inaccuracy of the translation. Or completely old man out of his mind survived. - Sergey

1 answer 1

Because this cycle is equivalent to the following

 for(int i = 0; i < arr.length; i++) { int cell = arr[i]; // ΠΏΠΎΠ»ΡƒΡ‡ΠΈΠ»ΠΈ копию i-Π³ΠΎ элСмСнта cell = -1; // ΠΈΠ·ΠΌΠ΅Π½ΠΈΠ»ΠΈ копию }