java中的System.copyof()与Array.copyof()区别

时间:2023-03-09 14:49:42
java中的System.copyof()与Array.copyof()区别

java中的System.copyof()与Array.copyof()区别

在复制数组时我们可以使用System.copyof(),也可以使用Array.copyof(),但是它们之间是有区别的。以一个简单的例子为例:

System.arraycopy()

int[] arr = {1,2,3,4,5};

int[] copied = new int[10];

System.out.println(Arrays.toString(copied));

System.arraycopy(arr, 0, copied, 1, 5);//5是复制的长度

System.out.println(Arrays.toString(copied));

 输出

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

[0, 1, 2, 3, 4, 5, 0, 0, 0, 0]

Arrays.copyOf()

int[] copied = Arrays.copyOf(arr, 10); //10是新数组的长度

System.out.println(Arrays.toString(copied));

copied = Arrays.copyOf(arr, 3);

System.out.println(Arrays.toString(copied));

输出

[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
[1, 2, 3]

最主要的区别

区别是Arrays.copyOf() 不只复制数组元素,也创建一个新数组。

System.arrayCopy 只复制已有的数组。

但是如果我们读Arrays.copyOf()的源码也会发现,它也用到了System.arrayCopy()。

   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