java.lang
包下的 System
类提供了一个 arraycopy
方法,可以将指定源数组中的数组从指定位置复制到目标数组的指定位置。
分析一下这几个参数:
src
:源数组srcPos
:源数组中的起始位置dest
:目标数组destPos
:目标数组中的起始位置length
:要复制的数组元素数量
用一个例子来说明具体用法:
int[] srcArr = {11, 22, 33, 44, 55, 66, 77, 88};
int[] destArr = new int[10];
System.arraycopy(srcArr,1,destArr,3,3);
System.out.println(Arrays.toString(destArr)); // [0, 0, 0, 22, 33, 44, 0, 0, 0, 0]
需要注意的是,复制的区间不可超出目标数组的范围,否则会报 ArrayIndexOutOfBoundsException
的异常。除此之外,src
或 dest
是 null
也会报 NullPointerException
的异常。