Im sure there is a simple answer to this and I will feel stupid in a few mins but here it goes, it’s late and im tired….
So, can i ask, why does this code…
public class TestProcess {
final float[] finalFloats = {0.9f,0.8f,0.7f};
float[] floats;
public static void main(String[] args) {
new TestProcess();
}
public TestProcess(){
floats = finalFloats;
printTotal();
floats[0]=0.1f;
printTotal();
floats = finalFloats;
printTotal();
}
void printTotal(){
float count = 0f;
for(float f : floats){
count+=f;
}
out("Count:"+count);
}
void out(String s){
System.out.println(s);
}
}
give this output
Count:2.4
Count:1.6
Count:1.6
When i would expect
Count:2.4
Count:1.6
Count:2.4
i feel very stupid…!
This question has also been asked link text, I will post here if it gets answered on the other forum.
Java arrays are mutable reference types.
When you write
floats = finalFloats;, you are making thefloatsfield refer to the same array instance asfinalFloats.Therefore, when you write
floats[0]=0.1f, you’re also modifying the originalfinalFloatsarray.All the
finalkeyword does is prevent you from assigningfinalFloatsto point to a new instance (eg,finalFloats = new float[7]); it doesn’t prevent you from mutating the instance.To make it behave the way you expect, you need to make a copy of the array, like this: