System.arraycopy()從指定源數組中複製一個數組

System類提供了一個arraycopy()方法

public static void arraycopy(Object src,
                             int srcPos,
                             Object dest,
                             int destPos,
                             int length)

    該方法用於從指定源數組中複製一個數組,複製從指定的位置開始,到目標數組的指定位置結束。從 src 引用的源數組到 dest 引用的目標數組,數組組件的一個子序列被複制下來。被複制的組件的編號等於 length 參數。源數組中位置在 srcPos 到 srcPos+length-1 之間的組件被分別複製到目標數組中的 destPos 到 destPos+length-1 位置。
    若是參數 src 和 dest 引用相同的數組對象,則複製的執行過程就好像首先將 srcPos 到 srcPos+length-1 位置的組件複製到一個帶有 length 組件的臨時數組,而後再將此臨時數組的內容複製到目標數組的 destPos 到 destPos+length-1 位置同樣。 數組

方法參數解釋

src - 源數組。
srcPos - 源數組中的起始位置。
dest - 目標數組。
destPos - 目標數據中的起始位置。
length - 要複製的數組元素的數量。

方法使用中拋出的異常

IndexOutOfBoundsException - 若是複製會致使對數組範圍之外的數據的訪問。 
ArrayStoreException - 若是由於類型不匹配而使得沒法將 src 數組中的元素存儲到 dest 數組中。 
NullPointerException - 若是 src 或 dest 爲 null

案例

public class SystemDemo {

    public static void main(String[] args) {
        int[] arr1 = { 1, 2, 3, 4, 5, 6, 7};  
        // 打印當前數組
        System.out.println(Arrays.toString(arr1)); 
        // 實現數組自我複製,把從索引0開始的3個數字複製到索引爲4的位置上 
        System.arraycopy(arr1, 0, arr1, 4, 3);  
        System.out.println(Arrays.toString(arr1));  
        // 實現將數組複製到其餘數組中,把從索引1開始的3個數據複製到目標的索引爲0的位置上 
        int[] arr2 = new int[7];  
        System.arraycopy(arr1, 1, arr2, 0, 3);  
        System.out.println(Arrays.toString(arr2));
    }

}

結果:markdown

這裏寫圖片描述

相關文章
相關標籤/搜索