老紫竹JAVA提高教程-System.arraycopy方法的使用
阿新 • • 發佈:2018-12-18
不廢話,直接看程式碼就全清楚了。裡面 // 後面的是執行的結果
[java] view plain copy print?- import java.util.Arrays;
- /**
- * 老紫竹JAVA提高教程 - System.arraycopy方法的使用。<br>
- * <br>
- * 從指定源陣列中複製一個數組,複製從指定的位置開始,<br>
- * 到目標陣列的指定位置結束
- *
- * @author 老紫竹的家(java2000.net,laozizhu.com)
- *
- */
- publicclass LessionSystemArraycopy {
- public
- // 此方位為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 = newint[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]
- }
- }