在Java中如果要copy一个数组有两种系统api可以使用System.arraycopy()和Arrays.copyOf()。那么这两个方法有什么不同吗?下面一个例子来给大家展示一下:
1、System.arraycopy()
int[] arr = {1,2,3,4,5};
int[] copied = new int[10];
System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
System.out.println(Arrays.toString(copied));
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
2、Arrays.copyOf()
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new arraySystem.out.println(Arrays.toString(copied)); copied = Arrays.copyOf(arr, 3);System.out.println(Arrays.toString(copied)); |
---|
Output:
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]
两种方法的不同之处在于Arrays.copyOf是通过创建一个新的数组来实现的copy,源码如下:
int[] copied = Arrays.copyOf(arr, 10); //10 the the length of the new array
System.out.println(Arrays.toString(copied));
copied = Arrays.copyOf(arr, 3);
System.out.println(Arrays.toString(copied));
System.arraycopy()是往一个已经存在的数组copy,函数源码如下:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
src - 源数组。 srcPos - 源数组中的起始位置。 dest - 目标数组。 destPos - 目标数据中的起始位置。 length - 要复制的数组元素的数量。 该方法是用了native关键字,调用的为C++编写的底层函数,可见其为JDK中的底层函数。
总结: 1.copyOf()的实现是用的是arrayCopy()。 2.arrayCopy()需要目标数组,对两个数组的内容进行可能不完全的合并操作。 3.copyOf()在内部新建一个数组,是用arrayCopy()将oldArray内容复制到newArray中去,并且长度为newLength,返回newArray。