System提供了一個native 靜態方法arraycopy(),我們可以使用它來實現陣列之間的複製。其函式原型是: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src:源陣列; srcPos:源陣列要複製的起始位置; dest:目的陣列; destPos:目的陣列放置的起始位置; length:複製的長度。 注意:src and dest都必須是同類型或者可以進行轉換型別的陣列
System提供了一個native 靜態方法arraycopy(),我們可以使用它來實現陣列之間的複製。其函式原型是: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src:源陣列; srcPos:源陣列要複製的起始位置; dest:目的陣列; destPos:目的陣列放置的起始位置; length:複製的長度。 注意:src and dest都必須是同類型或者可以進行轉換型別的陣列
程式碼示例:
import java.util.Arrays;
/**
* 老紫竹JAVA提高教程 - System.arraycopy方法的使用。<br>
* <br>
* 從指定源陣列中複製一個數組,複製從指定的位置開始,<br>
* 到目標陣列的指定位置結束
*
* @author 老紫竹的家(java2000.net,laozizhu.com)
*
*/
public class LessionSystemArraycopy {
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]
// 如果是型別轉換問題
Object[] o1 = { 1, 2, 3, 4.5, 6.7 };
Integer[] o2 = new Integer[5];
System.out.println(Arrays.toString(o2)); // [null, null, null, null, null]
try {
System.arraycopy(o1, 0, o2, 0, o1.length);
} catch (ArrayStoreException ex) {
// 發生儲存轉換,部分成功的資料會被複制過去
System.out.println("複製發生異常:資料轉換錯誤,無法儲存。");
}
// 從結果看,前面3個可以複製的資料已經被儲存了。剩下的則沒有
System.out.println(Arrays.toString(o2)); // [1, 2, 3, null, null]
}
}