在以下示例代码中,如何var1
在不更改initialVal1
构造函数 ( var2
) 中的情况下更改实例字段?- 我应该使用复制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;
}
}