关于Object.clone克隆方法的测试

【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.00
   2.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;







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值