In the following example code, how do I mutate the instance field var1
while not changing the initialVal1
in the constructor (var2
)? - should I make a copy using Arrays.copyOf
?
public class Test
{
private int[] var1;
private int[] var2;
public Test(int[] initialVal1)
{
var1 = initialVal1;
var2 = initialVal1;
}
private void int mutateVar1()
{
this.var1[0] = 100; // change the value at index 0 to 100 in var1 array, this also changes initialVal[0], right?
}
private int getSumOfInitial()
{
int sum = 0;
for (int i = 0; i < var2.length; i++) // but at this point, the initialVal[0] has also been mutated to 100.
{
sum += var2[i]
}
return sum;
}
}
var1
and initialVal
aren't arrays - they're just variables. Their values refer to an array... and they both refer to the same array. It's like having two pieces of paper both of which have the same house address on. Any changes you make to the house having followed the address on one piece of paper will obviously be visible if you then use the other piece of paper to visit the house again. I know this sounds like pedantry, but when you differentiate between variables, their values, and objects life becomes a lot clearer in my experience.
If you want two independent arrays, you need to do that deliberately. For example, you could change the constructor body to:
var1 = initialVal1.clone();
See more on this question at Stackoverflow