Java-Java中System.arraycopy() 和 Arrays.copyOf()两者之间的区别

如果我们想拷贝一个数组,我们可能会使用System.arraycopy()或者Arrays.copyof()两种方式。在这里,我们将使用一个比较简单的示例来阐述两者之间的区别。

1、示例代码:

System.arraycopy()

int[] arr = {1,2,3,4,5};
 
int[] copied = new int[10];
System.arraycopy(arr, 0, copied, 1, 5);//5 is the length to copy
 
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 the the length of the new array
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]

2、两者间的主要区别

两者的区别在于,Arrays.copyOf()不仅仅只是拷贝数组中的元素,在拷贝元素时,会创建一个新的数组对象。而System.arrayCopy只拷贝已经存在数组元素。

如果我们看过Arrays.copyOf()的源码就会知道,该方法的底层还是调用了System.arrayCopyOf()方法。

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; 
}
原文地址:https://www.cnblogs.com/yongdaimi/p/5995414.html