Java中数组的clone
先看实验代码:
[java]
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]));
}
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]));
}
补充:软件开发 , Java ,