Alex
Alex

Reputation: 970

Different output for array.clone() for 1- and multidimensional arrays

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?

Upvotes: 0

Views: 29

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533492

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;
 }

Upvotes: 4

Maksym
Maksym

Reputation: 4574

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

Upvotes: 1

Related Questions