//System.arraycopy,只拷贝已存在的数组元素 int[] src = {0, 1, 2}; int[] dest = new int[3]; System.arraycopy(src, 0, dest, 0, src.length); System.out.println(Arrays.toString(dest)); //[0, 1, 2]
//Arrays.copyOf,会创建一个新的数组对象 int[] src = {0, 1, 2}; int[] dest = Arrays.copyOf(src, src.length); System.out.println(Arrays.toString(dest)); //[0, 1, 2]
实际上Arrays.copyOf方法的内部实现也是通过System.arraycopy方法实现,在Arrays类中有多个copyOf的重载方法,现以拷贝int[]为例:
1 public static int[] copyOf(int[] original, int newLength) { 2 int[] copy = new int[newLength]; 3 System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); 4 return copy; 5 }