We have a vector a
of the type double[]
and we want to clone the values in a to another vector. Why doesn't this work: double [] b = a;
?

- 3,378
- 11
- 25
- 41
-
1Because `a` and `b` are merely references to the vector, not the vector itself. You only copy the reference. – markspace Mar 15 '21 at 02:46
-
Related: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – markspace Mar 15 '21 at 02:47
-
1This might help: https://www.geeksforgeeks.org/vector-clone-method-in-java-with-examples/ – Tim Roberts Mar 15 '21 at 02:47
-
1Did arrays in Java get renamed to vectors while I was asleep? – Robby Cornelissen Mar 15 '21 at 02:49
-
1Please, stop asking java's basics before doing some research... You get comment about references in https://stackoverflow.com/questions/66629722/why-does-this-conde-snippet-produce-the-following-output question and still you don't get it – Selvin Mar 15 '21 at 02:50
2 Answers
A vector in Java when passed to a function or copied into a variable like this, does not copy the values into the new array but rather just references the original object. This code should compile (if a exists as a double vector) but any changes made to a or b will affect the other vector.
The reason this was done is that cloning an object is a very expensive operation and even sometimes impossible. It is safer just to pass references around and let the user create a new object if they need one. In Java, vectors are an object so the property holds.

- 106
- 1
- 7
Because you're just copying a reference to the same array.
double[] d1 = {1,2,3,4};
double[] d2 = d1;
System.out.println(System.identityHashCode(d1));
System.out.println(System.identityHashCode(d2));
prints
135721597
135721597
Same identityHashCode so same array. Changing an element in one array will affect the other array.
But if you want to clone the array. You can do the following:
double[] d1 = {1,2,3,4};
double[] d2 = d1.clone();
d1[0] = 99; // to show they're different arrays.
System.out.println(Arrays.toString(d1));
System.out.println(Arrays.toString(d2));
Prints
[99.0, 2.0, 3.0, 4.0]
[1.0, 2.0, 3.0, 4.0]
However, if the arrays contain Objects, then the arrays are different but the Objects are not cloned.
Object[] d1 = {new Object(), new Object()};
Object[] d2 = d1.clone();
System.out.println(System.identityHashCode(d1));
System.out.println(System.identityHashCode(d2));
System.out.println();
System.out.println(System.identityHashCode(d1[0]));
System.out.println(System.identityHashCode(d2[0]));
Prints something like
135721597
142257191
135721597
135721597

- 36,363
- 4
- 24
- 39