如果我們想拷貝一個數組,我們可能會使用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; }