1. 程式人生 > 其它 >System.arraycopy和Arrays.copyofrange的基本用法

System.arraycopy和Arrays.copyofrange的基本用法

技術標籤:java基礎

最近接觸的物聯網專案,總是用到System.arraycopy和Arrays.copyofrange來進行陣列之間的拷貝,因此,來記錄下這兩種陣列拷貝的基本用法。
System.arraycopy
這個方法相當於把一個數組中的元素,拷貝到另一個數組裡面,可以部分拷貝


/*
     * @param      src      the source array.
     * @param      srcPos   starting position in the source array.
     * @param      dest     the destination array.
     * @param      destPos  starting position in the destination data.
     * @param      length   the number of array elements to be copied.
*/
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);

我們首先來看下System.arraycopy方法的原始碼,可以看到,是native修飾,可以知道底層不是用java語言實現。
首先來看下第一個引數:src: the sorce array,即源陣列,這個陣列的元素是要拷貝到其他元素中的。

第二個引數:srcPos ,表面的意思為源陣列的起始位置,即要拷貝到其他陣列的的元素的起始索引位置。
第三個引數:dest,表面意思為目的地陣列,即上面源陣列中的元素,最終會拷貝到這個目的地數組裡面。
第四個引數:destPos,目的地陣列的起始位置,即要把源陣列中的元素放到目的地陣列中的起始位置
第五個引數:length,拷貝的陣列元素長度。即拷貝源陣列中的元素在新陣列中的長度。

例如:要把bytes陣列中的元素拷貝到data的位元組陣列中

   byte[] bytes = new byte[]{1, 2, 3, 4, 5};
        byte[] data = new byte
[10]; System.arraycopy(bytes, 0, data, 0, 5); for (byte b : data) { System.out.print(b); }

輸出結果為:

1234500000

Arrays.copyOfRange
這個方法相當於擷取陣列中的某一部分元素,到一個新陣列中

/*
	 * @param original the array from which a range is to be copied
     * @param from the initial index of the range to be copied, inclusive
     * @param to the final index of the range to be copied, exclusive.
*/
 public static int[] copyOfRange(int[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        int[] copy = new int[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

看到這裡,不知道發現沒有,這個方法最後還是呼叫System.arraycopy方法完成的擷取。
首先來看引數:
第一個引數:original,即要擷取的原始陣列
第二個引數:from,即要從原始陣列中的那個位置開始擷取。。
第三個引數:to,要擷取到的那個位置。

這裡用的時候,遇到個坑,也怪自己沒好好看程式碼,導致沒截全。
在這裡插入圖片描述
其實註釋裡面寫的很清楚,即進行陣列擷取的時候,包括第二個引數,不包括第三個引數

假如我們要將陣列bytes中的第3位開始,擷取到陣列的末尾。

byte[] bytes = new byte[]{1, 2, 3, 4, 5, 6, 7, 8};
        byte[] copy = Arrays.copyOfRange(bytes, 3, bytes.length );
        for (byte b : copy) {
            System.out.print(b);
        }

輸出結果:

45678

注意: 一般陣列.length-1表示陣列的最後末尾,但這裡這個方法是不包括最後一位,使用的時候要注意。