因为您只是在复制对同一个数组的引用。
double[] d1 = {1,2,3,4};
double[] d2 = d1;
System.out.println(System.identityHashCode(d1));
System.out.println(System.identityHashCode(d2));
打印
135721597
135721597
相同的identityHashCode 所以相同的数组。更改一个数组中的元素会影响另一个数组。
但是如果你想克隆数组。您可以执行以下操作:
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));
打印
[99.0, 2.0, 3.0, 4.0]
[1.0, 2.0, 3.0, 4.0]
但是,如果数组包含对象,那么数组是不同的,但对象不会被克隆。
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]));
打印类似的东西
135721597
142257191
135721597
135721597