標籤:
轉載自: http://blog.csdn.net/java2000_net/article/details/4059465
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] }}
[Java基礎] System.arraycopy使用