import java.util.Arrays;
/**
* System.arraycopy方法的使用。
*
* 從指定源數組中複製一個數組,複製從指定的位置開始, 到目標數組的指定位置結束
*
*/
public class Example {
public static void main(String[] args) {
// 此方位爲native方法。
// public static native void arraycopy(
// Object src, int srcPos, Object dest,
// int destPos, int length);
// 初始化
int[] ids = { 1, 2, 3, 4, 5 };
System.out.println(Arrays.toString(ids)); // [1, 2, 3, 4, 5]
// 測試自我複製
// 把從索引0開始的2個數字複製到索引爲3的位置上
System.arraycopy(ids, 0, ids, 3, 2);
System.out.println(Arrays.toString(ids)); // [1, 2, 3, 1, 2]
// 測試複製到別的數組上
// 將數據的索引1開始的3個數據複製到目標的索引爲0的位置上
int[] ids2 = new int[6];
System.arraycopy(ids, 1, ids2, 0, 3);
System.out.println(Arrays.toString(ids2)); // [2, 3, 1, 0, 0, 0]
// 此功能要求
// 源的起始位置+長度不能超過末尾
// 目標起始位置+長度不能超過末尾
// 且所有的參數不能爲負數
try {
System.arraycopy(ids, 0, ids2, 0, ids.length + 1);
} catch (IndexOutOfBoundsException ex) {
// 發生越界異常,數據不會改變
System.out.println("拷貝發生異常:數據越界。");
}
System.out.println(Arrays.toString(ids2)); // [2, 3, 1, 0, 0, 0]
}
}
運行結果:
[1, 2, 3, 4, 5]
[1, 2, 3, 1, 2]
[2, 3, 1, 0, 0, 0]
拷貝發生異常:數據越界。
[2, 3, 1, 0, 0, 0]