java.lang 包下的 System 类提供了一个 arraycopy 方法,可以将指定源数组中的数组从指定位置复制到目标数组的指定位置。

JavaSE-26-1

分析一下这几个参数:

  • 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 的异常。除此之外,srcdestnull 也会报 NullPointerException 的异常。