源码
copyOfRange方法有以下几个重载的方法,使用方法基本一样,只是参数数组类型不一样
- original:第一个参数为要拷贝的数组对象
- from:第二个参数为拷贝的开始位置(包含)
- to:第三个参数为拷贝的结束位置(不包含)
各个方法的源码基本一样,我们选取一个看下
可以看到内部实现实际是调用了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 (<tt>from</tt>) must lie between zero
* and <tt>original.length</tt>, inclusive. The value at
* <tt>original[from]</tt> is placed into the initial element of the copy
* (unless <tt>from == original.length</tt> or <tt>from == to</tt>).
* Values from subsequent elements in the original array are placed into
* subsequent elements in the copy. The final index of the range
* (<tt>to</tt>), which must be greater than or equal to <tt>from</tt>,
* may be greater than <tt>original.length</tt>, in which case
* <tt>0</tt> is placed in all elements of the copy whose index is
* greater than or equal to <tt>original.length - from</tt>. The length
* of the returned array will be <tt>to - from</tt>.
*
* @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 <tt>from > to</tt>
* @throws NullPointerException if <tt>original</tt> 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]