在複製數組時我們可以使用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;
}