0

Case 1, one-dimensional:

double[]vals = new double[4];
vals[0] = 1;
vals[1] = 123;
vals[2] = -1;
vals[3] = 2;

double[] vals4 = vals.clone();

double newval = 55;
vals[0] += newval;

for (int k=0;k<vals.length;k++){
  System.out.println("k= " + vals[k]);
  System.out.println("k= " + vals4[k]);               
}

The output is

k= 56.0
k= 1.0
k= 123.0
k= 123.0
k= -1.0
k= -1.0
k= 2.0
k= 2.0

Case 2, 2-dimensional:

double[][] vals3 = new double[][]{
                     {1,2},
                     {3,4}
                   };

double[][] vals2 = vals3.clone();
vals3[0][0] += 112;

for (int i=0;i<vals3.length;i++){
  for (int j=0;j<vals3[0].length;j++){
    System.out.println(vals2[i][j]);
    System.out.println(vals3[i][j]);
  }          
}  

The output is

113.0
113.0
2.0
2.0
3.0
3.0
4.0
4.0

I use the same function, array.clone(), but why do the array elements change in the 2-dim case, when I change the array's inputs, but don't in the 1-dim case?

2 Answers 2

4

Java only has single dimensional arrays. A double[][] is an array of references to double[] so when you clone an array of references, you get another array of references to the same underlying arrays.

To do a deep clone, you can to create a new double[][] of the same size and clone the individual double[]s

e.g.

 public static double[][] deepClone(double[][] d) {
     double[][] ret = new double[d.length][];
     for(int i = 0; i < ret.length; i++)
         ret[i] = d[i].clone();
     return ret;
 }
Sign up to request clarification or add additional context in comments.

7 Comments

would a System.arraycopy() be a better option for 2-dim case?
@Alex Using System.arraycopy doesn't alter the fact that you would be copying an array of references to arrays.
OK then, in the case when I change a value in a 2-dim array, how should I copy it to keep the values in the other one unchanged? With two for loops?
@Alex effectively yes, but the simplest solution is to use clone() in the manner in my answer.
Thanks. Are they the same in terms of number of function evaluations/memory use/runtime?
|
1

Yep, it's because array.clone() copies references, in other words array clone just does "shallow" copy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.