Range for loop does not work

I have Double[] foo

, and I need to convert each element to an array:

I tried

for (Double p : foo){
    p = p * m + o;
}

      

where m

and o

are the scaling factors. I have also tried

for (Double p : foo){
    p *= m;
    p += o;
}

      

but none of them work. What am I doing wrong? I thought that all non-primitives are references in Java.

+3


source to share


2 answers


Java auto-towing and unpacking get in the way here. Essentially p

unpacked into a primitive before arithmetic operations and then automatically added to the wrapper type. The effect of this is that the values ​​are copied and therefore the modification does not affect the original container element.

You need to recode the loop in the usual way



for (int i = 0; i < foo.length; ++i){
    foo[i] = foo[i] * m + o;
}

      

+5


source


You cannot modify array values ​​with an extended for loop, only iterate through them.



Try a normal loop and see what happens :)

+10


source







All Articles