Arrays 類提供了兩類複製數組的方法,而且提供了很多重載形式,可以實現不同類型數組的複製,這裏僅以 int 類型爲例說明。
copyOf(arr, int newlength)
- 複製數組 arr 中的所有元素到新數組中
- newlength 是新數組的長度,若大於 arr 的長度則用 0 填充,若小於 arr 的長度則從第一個元素開始截取
- 返回複製後得到的新數組
copyOfRange(arr, int fromIndex, int toIndex)
- 複製數組 arr 中指定索引範圍內的元素到新數組中
- 索引範圍包括 fromIndex,不包括 toIndex
- 返回複製後得到的新數組
public static void main(String args[]) {
int[] arr = new int[5];
Arrays.fill(arr, 8);
System.out.println("複製整個數組後得到的新數組:");
int[] brr = Arrays.copyOf(arr, 8);
for (int m : brr) {
System.out.print(m + " ");
}
int[] crr = Arrays.copyOfRange(brr, 0, 3);
System.out.println("\n複製部分數組後得到的新數組:");
for (int m : crr) {
System.out.print(m + " ");
}
}
輸出:
複製整個數組後得到的新數組:
8 8 8 8 8 0 0 0
複製部分數組後得到的新數組:
8 8 8