Java数组的clone()方法

  • 结论:

A.一维数组:深克隆(重新分配空间,并将元素复制过去)

对clone后的数组进行修改不会影响源数组。
B.二维数组:浅克隆(只传递引用)

对clone后的数组进行修改时,将对源数组也产生影响(因为复制的是引用,实际上指向的是同一个地址)

  • 请看事实证明:
int[] a={3,1,4,2,5};
int[] b=a.clone();
b[0]=10;
System.out.println(b[0]+"  "+a[0]);
输出为10  3
可见改变了b的值,但是没有改变a的元素的值

int[][] a={{3,1,4,2,5},{4,2}};
int[][] b=a.clone();
b[0][0]=10;
System.out.println(b[0][0]+"  "+a[0][0]);
输出为10  10

int[][] a={{3,1,4,2,5},{4,2}};
int[][] b=a.clone();
b[0][0]=10;
System.out.println(b[0][0]+"  "+a[0][0]);
System.out.println(a[0]==b[0]);
第5句输出为true。
  • 如何实现二维数组的深克隆呢?

对每个一维数组调用clone方法。

int[][] a={{3,1,4,2,5},{4,2}};
int[][] b=new int[a.length][];
for(int i=0;i<a.length;i++){
        b[i]=a[i].clone();
}
b[0][0]=10;
System.out.println(b[0][0]+"  "+a[0][0]);
System.out.println(b[0]==a[0]);
输出为
10  3
false

————————————————

原文链接:https://blog.csdn.net/diyinqian/article/details/83279457

原文地址:https://www.cnblogs.com/qingtian-jlj/p/13098114.html