1.System.arraycopy()
(1)查看源码可知, System.arraycopy() 是一个 native
方法,其各项参数介绍如下:
public final class System {
//...
/*
* @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.
*/
public static native void arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
}
(2)测试
class ArrayCopyTest {
public static void main(String[] args) {
int[] src = new int[4];
src[0] = 0;
src[1] = 1;
src[2] = 2;
src[3] = 3;
int[] desc = new int[10];
System.out.println("复制之前,desc 中的元素如下");
for (int elem : desc) {
System.out.print(elem + " ");
}
System.arraycopy(src, 0, desc, 5, 4);
System.out.println("\n\n复制之后,desc 中的元素如下");
for (int elem : desc) {
System.out.print(elem + " ");
}
}
}
输出结果如下:
复制之前,desc 中的元素如下
0 0 0 0 0 0 0 0 0 0
复制之后,desc 中的元素如下
0 0 0 0 0 0 1 2 3 0
2.Arrays.copyOf()
(1)copyOf() 是 Arrays 类中的一个静态方法,其源码如下所示:
public class Arrays {
//...
/*
* @param original the array to be copied
* @param newLength the length of the copy to be returned
* @return a copy of the original array, truncated or padded with zeros
* to obtain the specified length
*/
public static int[] copyOf(int[] original, int newLength) {
int[] copy = new int[newLength];
//调用 System.arraycopy() ,将源数组中的数据进行拷, 并返回新的数组
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
}
(2)测试
class ArrayCopyTest {
public static void main(String[] args) {
int[] original = new int[4];
original[0] = 0;
original[1] = 1;
original[2] = 2;
original[3] = 3;
int[] desc = Arrays.copyOf(original, 10);
for (int elem : desc) {
System.out.print(elem + " ");
}
}
}
输出结果如下:
0 1 2 3 0 0 0 0 0 0
3.联系与区别
(1)联系:看两者源代码可以发现 copyOf() 内部实际调用了 System.arraycopy() 方法。
(2)区别:arraycopy() 需要目标数组,将原数组拷贝到你自己定义的数组里或者原数组,而且可以选择拷贝的起点和长度以及放入新数组中的位置 copyOf() 是系统自动在内部新建一个数组,并返回该数组。