Good day colleagues. Solved a simple problem. Normal for seemed to me too ordinary. I tried to solve the problem using for each , and ... I did not succeed in ๏ ๏.

 double x [] = {255, 0 , 212}; for(double g : x) { g = g/255; } 

At the output, the array remained the same, but I wanted it to be {1, 0, 0.82} .

I understand that in this cycle you can read the values ​​- because g is just a copy.

Question: Is it possible to change the values ​​in this array by the for each loop, so that after exiting the loop, in this example, {1, 0, 0.82} ?

    3 answers 3

    You can if you use an index variable:

     double x [] = {255, 0 , 212}; int i = 0; for(double g : x){ g = g/255; x[i++] = g; } 
    • Thanks in my example works. And there will be no errors if, say 50 elements? Does for each always start with a null element traversal? - Andrew Kachalin
    • I mean, will not the situation end one day with the fact that the third element will replace the first one? - Andrew Kachalin
    • No, it will not be if in one thread. It works much like an iterator. - Roman C

    You are changing the iteration variable g , not the content of the array. The point is that the iteration variable is just a copy from the array.

    Therefore, the answer is no, inside for each, you cannot change the array in this way.

    You can only change this:

     for (int i = 0; i < g.length; i++) { g[i] = g[i]/255; } 
    • Where is the for each loop used here? - Roman C
    • @RomanC So I wrote that the data in the array via for each in the form that the author wants is impossible. To do this, write a normal cycle. And he gave an example of how you can, and I think it will be better. - Axenow
    • Can't use a for each loop? - Roman C
    • @RomanC Taking into account the example in the question - it is impossible, given the additional variables, strapping, etc. - Can. I answered the question not formally, but taking into account the semantics and the desire of the person to understand, it can be done as he wants or not. - Axenow
    • Not interested. We all can do that too. - Andrew Kachalin

    Using external type variables inside lambda is not very good practice, but you can also use the Stream API:

     double x [] = {255, 0 , 212}; IntStream.range(0, x.length).forEach(i -> x[i] /= 255); 
    • Thanks where did you know all this? - Andrew Kachalin
    • Well, I write code in Java, not?) - iksuy