如果我们想拷贝一个数组,我们可能会使用Arrays.copyof()或者System.arraycopy()两种方式。在这里,我们将使用一个比较简单的示例来阐述两者之间的区别。
一、首先System.arraycopy()
首先观察先System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)的声明:
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
src - 源数组。
srcPos - 源数组中的起始位置。
dest - 目标数组。
destPos - 目标数据中的起始位置。
length - 要复制的数组元素的数量。
该方法是用了native关键字,调用的为C++编写的底层函数,可见其为JDK中的底层函数。
接下来是示例代码:
package collection;
import java.util.Arrays;
public class testArrayCopy {
public static void main(String[] args) {
int[] arr1 = {1,2,3,4,5};
int[] arr2 = new int[10];
//这里的arr1是原数组,0是原数组拷贝的其实地址。而arr2是目标数组,1是目标数组开始存放的位置,5则是数组存放的长度。
System.arraycopy(arr1, 0, arr2, 1, 5);
System.out.println(Arrays.toString(arr2));
}
}
运行结果如下:
[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]
二、其次Arrays.copyOf()
源码如下:
//复杂数据类型
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
由U类型复制为T类型?
original - 要复制的数组
newLength - 要返回的副本的长度
newType - 要返回的副本的类型
//基本数据类型(其他类似byte,short···)
public static int[] copyOf(int[] original, int newLength) {
int[] copy = new int[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
示例代码如下:
package collection;
import java.util.Arrays;
public class ArraysCopyOf {
public static void main(String[] args) {
int[] arr3 = {1,2,3,4,5};
int[] arr4 = new int[8];
arr4 = Arrays.copyOf(arr3, 8);
System.out.println(Arrays.toString(arr4));
System.out.println("==================");
arr4 = Arrays.copyOf(arr3, 3);
System.out.println(Arrays.toString(arr4));
}
}
运行结果如下:
[1, 2, 3, 4, 5, 0, 0, 0]
==================
[1, 2, 3]
三、总结
- 观察其源代码发现copyOf(),在其内部创建了一个新的数组,然后调用arrayCopy()向其复制内容,返回出去。
- 两者的区别在于,Arrays.copyOf()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。
- copyOf()的实现是用的是arrayCopy();
- arrayCopy()需要目标数组,对两个数组的内容进行可能不完全的合并操作。
- copyOf()在内部新建一个数组,调用arrayCopy()将original内容复制到copy中去,并且长度为newLength。返回copy;