歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Java中數組的clone

先看實驗代碼:

  public static void main(String[] args) throws CloneNotSupportedException {
    // 測試一,數組可以被clone
    int[] arr1 = new int[5];
    int[] arr2 = arr1.clone();
    arr2[0] = 1;
    System.out.println("arr1 instanceof java.lang.Cloneable: " + (arr1 instanceof java.lang.Cloneable));
    System.out.println("arr1: " + Arrays.toString(arr1));
    System.out.println("arr2: " + Arrays.toString(arr2));
   
    // 測試二,數組的數組可以被clone
    int[][] arr3 = new int[2][2];
    arr3[0][0]=1;
    int[][] arr4 = null;
    arr4 = arr3.clone();
    System.out.println("arr3 instanceof java.lang.Cloneable: " + (arr3 instanceof java.lang.Cloneable));
    System.out.println("arr3: " + Arrays.toString(arr3[0]));
    System.out.println("arr4: " + Arrays.toString(arr4[0]));
   
   
  // 測試三,說明引用類型不能被clone!因為arr5[0]其實是個引用類型
    int[][] arr5 = new int[2][2];
    int[][] arr6 = null;
    arr5[0][0]=1;
    arr6[0] = arr5[0].clone();
    System.out.println("arr5 instanceof java.lang.Cloneable: " + (arr5 instanceof java.lang.Cloneable));
    System.out.println("arr5: " + Arrays.toString(arr5[0]));
    System.out.println("arr6: " + Arrays.toString(arr6[0]));
  }

Copyright © Linux教程網 All Rights Reserved