System.arraycopy()
这是一个由java标准库提供的方法。用它进行复制数组比用for循环要快的多。
arraycopy()需要的参数有:源数组,从源数组中的什么位置开始复制的偏移量,目标数组,从目标数组中的什么位置开始复制的偏移量,需要复制的元素个数
查看源码,它调用的是本地方法,应该是用c语言封装好的
Arrays.copyOf
在复制数组时会返回一个新数组
copyOf()需要有的参数:源数组,需要复制的元素个数
查看源码:
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;
}
其仍调用的是System.arraycopy()这个方法,并且返回一个新数组
附测试Demo:
public class CopyDemo {
public static void main(String[] args) {
int[] a = new int[] {1, 2, 3, 4, 5, 6, 7};
int[] b = new int[5];
System.arraycopy(a, 0, b, 0, 5);
System.out.println(Arrays.toString(b));
int[] c = {1, 2, 3, 4, 5};
int[] d = Arrays.copyOf(c, 5);
System.out.println(Arrays.toString(d));
}
}