【0】README
0.1)本文旨在用源代码测试说明, Object.clone 的 的克隆机制(深拷贝 还是 浅拷贝) 的问题;
0.2)本文还添加了对System.arraycopy本地方法的测试(干货——推荐使用该方法进行数组复制);
【1】代码如下
public class Temp {
public static void main(String[] args) {
testClone();
testClone_2();
}
public static void testClone() {
double[] a = {1, 2, 3};
double[] b = a.clone();
b[0] = 0;
System.out.println(a[0]);//1
}
public static void testClone_2(){
double[] a = new double[3];
double[] b;
a[0] = 1;
b = a.clone();
b[0] = 0;
System.out.println(a[0]);//1
}
}
【2】测试结果
显然, clone的拷贝是深拷贝,因为我在修改数组b时,数组a中的相应元素没有被改变。。(当然,其他书也有例子说 clone是 浅拷贝,仅在本例而言,他是深拷贝)
【3】不规则数组copy
public static void main(String[] args) {
double[][] array = {
{1,2,3},
{2,2,2},
{3,3,3}};
double[][] backup = new double[array.length][];
int[] begin = {1, 2, 3};//起始下标
int single_len = 0;
for (int i = 0; i < backup.length; i++) {
single_len = array[i].length - begin[i] + 1;
backup[i] = new double[single_len];
// System.arraycopy(src, srcPos, dest, destPos, length);
System.arraycopy(array[i], begin[i]-1, backup[i], 0, single_len);
}
}
打印结果:
1.00 2.00 3.002.00 2.00
3.00
【4】System.arraycopy本地方法
4.1)二维数组的copy(干货——循环使用 System.arraycopy 对二维数组的单个一维数组进行copy,不能将二维数组的引用传入到System.arraycopy,不然copy结果还只是 引用间的copy)
public static void main(String[] args) {
double[][] temp = {{1,2,3}, {2,3,1}};
double[][] a;
a = Arrays.copyOf(temp, temp.length);
temp[0][0] = -1;
System.out.println("\n first output === a array ===");
AlgTools.printArray(a);
a[0][0] = -2;
System.out.println("\n second output === temp array ===");
AlgTools.printArray(temp);
double[][] b = new double[temp.length][temp[0].length];
for (int i = 0; i < temp.length; i++) {
System.arraycopy(temp[i], 0, b[i], 0, temp[i].length);
}
temp[0][0] = -4;
System.out.println("\n third output === b array ===");
AlgTools.printArray(b);
b[0][0] = -5;
System.out.println("\n fourth output=== temp array ===");
AlgTools.printArray(temp);
}
//打印结果
first output === a array ===
-1.00 2.00 3.00
2.00 3.00 1.00
second output === temp array ===
-2.00 2.00 3.00
2.00 3.00 1.00
third output === b array ===
-2.00 2.00 3.00
2.00 3.00 1.00
fourth output === temp array ===
-4.00 2.00 3.00
2.00 3.00 1.00
4.2)一维数组的copy
从以上代码我们可知:System.arraycopy 对一维数组的 copy 就是值对值的copy,而不是引用对引用的copy;