二维数组深度克隆

package cn.com.csuinfo.deepclone;

public class TestClone {
 public static void main(String[] args) {
  int[][] arr1 = { { 1, 2, 1 }, { 1, 3, 3, 1 }, { 1, 4, 6, 4, 1 } };
  int[][] arr2;
  int[][] arr3 ={{ 1, 2, 1 }, { 1, 3, 3, 1 }, { 1, 4, 6, 41, 1 }};
  int[] a = { 1, 2, 3, 4 };
  int[] a1;

  DeepClone dc1 = new DeepClone();
  DeepClone dc2 = new DeepClone();
  DeepClone dc3 = new DeepClone();
  dc1.setArr(arr1);
  dc3.setArr(arr3);
  dc1.setA(a);
  
  try {
   arr2 = dc1.clone().getArr();  //克隆arr1到arr2;
   a1 = dc1.clone().getA();
   dc2 = dc1.clone();
   // System.out.println("before arr1[0][1]:" + arr1[0][1]);
   // arr1[0][1] = 20;
   // System.out.println("after arr1[0][1]:" + arr1[0][1]);
   // System.out.println("after arr12[0][1]:" + arr12[0][1]);
   // System.out.println("before a[1]:" + a[1]);
   // a1[1] = 22;
   // System.out.println("after a[1]:" + a[1]);
   
   /* 打印了源数组 */
   System.out.println("arr1:");
   for (int[] ar : arr1) {
    for (int aa : ar) {
     System.out.print(aa + ",");
    }
    System.out.println();
   }
   
   System.out.println("arr2:");
   for (int[] ar : dc2.getArr()) {
    for (int aa : ar) {
     System.out.print(aa + ",");
    }
    System.out.println();
   }

   System.out.println("dc1 equals dc2? "
     + dc1.equals(dc2));
   System.out.println("dc1's hashcode:" + dc1.hashCode());
   System.out.println("dc2's hashcode:" + dc2.hashCode());
   
   System.out.println("dc1:" + dc1.toString());
   System.out.println("dc2:" + dc2.toString());
   
   /* 对克隆数组进行修改 */
   for (int i = 0; i < arr2.length; i++) {
    for (int j = 0; j < arr2[i].length; j++) {
     dc2.getArr()[i][j] += 10;
    }
   }
   
   /* 打印了克隆而再进行修改后的数组 */
   System.out.println("修改dc2中的arr2后");
   System.out.println("arr2:");
   for (int[] ar : dc2.getArr()) {
    for (int aa : ar) {
     System.out.print(aa + ",");
    }
    System.out.println();
   }
   
   System.out.println("dc1 equals dc2? "
     + dc1.equals(dc2));
   System.out.println("dc1's hashcode:" + dc1.hashCode());
   System.out.println("dc2's hashcode:" + dc2.hashCode());
   
   System.out.println("dc1:" + dc1.toString());
   System.out.println("dc2:" + dc2.toString());
   
  } catch (CloneNotSupportedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  /*两个拥有不同数组的对象进行比较*/
  System.out.println("dc1 equals dc3?" + dc1.equals(dc3));

 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值