Java数组的复制方法

来源:互联网 发布:罗柏史塔克 知乎 编辑:程序博客网 时间:2024/05/15 07:15

如下代码:

int[] a={3,1,4,2,5};int[] b=a;

此时数组b只是对数组a的又一个引用,即浅拷贝。如果改变数组b中元素的值,其实是改变了数组a的元素的值,要实现深度复制,可以用Object.clone()或者System.arrayCopy

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

clone和System.arrayCopy都是对一维数组的深度复制。对于二维数组则不一样:

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,10System.out.println(a[0]==b[0]);//结果true

所以clone并不能直接作用于二维数组。因为java中没有二维数组的概念,只有数组的数组。所以二维数组a中存储的实际上是两个一维数组的引用。当调用clone方法时,是对这两个引用进行了复制。第5句输出为true证明了这一点。用clone对二维数组进行复制,要在每一维上调用clone方法:

int[][] a={{3,1,4,2,5},{4,2}};int[][] b=newint[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]);//结果10,3System.out.println(b[0]==a[0]);//结果false

数组的复制方法现在至少有四个思路:

1、使用循环结构这种方法最灵活,唯一不足的地方可能就是代码较多。

2、使用Object类的clone方法,这种方法最简单,得到原数组的一个副本。灵活形也最差。效率最差,尤其是在数组元素很大或者复制对象数组时。

3、使用Systems.arraycopy,这种方法被认为速度最快,并且灵活性也较好,可以指定原数组名称、以及元素的开始位置、复制的元素的个数,目标数组名称、目标数组的位置。定义如下:

public static nativevoid arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);

@param     src     the source array.

@param     srcPos  starting position in the source array.

@param     dest    the destination array.

@param     destPos starting position in the destination data.

@param     length  the number of array elements to be copied.

@exception  IndexOutOfBoundsException  if copying would cause access of data outsidearray bounds.

@exception  ArrayStoreException  if an element in the src array could not be stored into the dest array because of a type mismatch.

@exception  NullPointerException if either src ordest is null.

4、Arrarys类的copyOf()方法与copyOfRange()方法可实现对数组的复制。实质也是调用了System.arraycopy,源码中可以看出。

0 0