二維數組深度複製

來源:互聯網
上載者:User

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));

 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.