public class Test {
public static void main(String[] args) {
int arr[] = new int[] { 1, 2, 3, 4 };
int newarr[] = Arrays.copyOf(arr, 6);
System.out.println(Arrays.toString(newarr));
int b[] = new int[10];
System.arraycopy(arr, 0, b, 0, 3);
System.out.println(Arrays.toString(b));
}}
结果如图:
区别
Arrays.copyOf()新建一个数组,同时拷贝元素。
System.arraycopy()是往一个已经存在的数组里拷贝元素
Arrays.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;
}