java Arrays.copyOfRange使用方法

源码

copyOfRange方法有以下几个重载的方法,使用方法基本一样,只是参数数组类型不一样

  • original:第一个参数为要拷贝的数组对象
  • from:第二个参数为拷贝的开始位置(包含)
  • to:第三个参数为拷贝的结束位置(不包含)

java Arrays.copyOfRange使用方法_第1张图片

各个方法的源码基本一样,我们选取一个看下

可以看到内部实现实际是调用了System.arraycopy数组拷贝方法

Math.min(original.length - from, newLength)这行代码表示,若拷贝的内容超出源数组的数组边界,则只拷贝from位置到源数组最后一个元素,防止数组越界

/**
 * Copies the specified range of the specified array into a new array.
 * The initial index of the range (from) must lie between zero
 * and original.length, inclusive.  The value at
 * original[from] is placed into the initial element of the copy
 * (unless from == original.length or from == to).
 * Values from subsequent elements in the original array are placed into
 * subsequent elements in the copy.  The final index of the range
 * (to), which must be greater than or equal to from,
 * may be greater than original.length, in which case
 * 0 is placed in all elements of the copy whose index is
 * greater than or equal to original.length - from.  The length
 * of the returned array will be to - from.
 *
 * @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.
 *     (This index may lie outside the array.)
 * @return a new array containing the specified range from the original array,
 *     truncated or padded with zeros to obtain the required length
 * @throws ArrayIndexOutOfBoundsException if {@code from < 0}
 *     or {@code from > original.length}
 * @throws IllegalArgumentException if from > to
 * @throws NullPointerException if original is null
 * @since 1.6
 */
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;
}

使用

public class Test {
    public static void main(String[] args) {
        int[] array = {0, 1, 2, 3, 4, 5, 6};
        int[] array2 = Arrays.copyOfRange(array, 2, 4);
        System.out.println(Arrays.toString(array2));
    }
}

结果输出如下,注意4位置是不包含的

[2, 3]

 

 

你可能感兴趣的:(Java)