温馨提示×

Java中system.arraycopy的作用是什么

小亿
267
2023-12-29 12:47:29
栏目: 编程语言

System.arraycopy() 方法是 Java 中用来复制数组的方法。它允许将一个数组的一部分内容复制到另一个数组的指定位置。

System.arraycopy() 方法的语法如下:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

参数说明:

  • src:源数组,即要复制的数组。
  • srcPos:源数组的起始位置,即从哪个位置开始复制。
  • dest:目标数组,即将复制到的数组。
  • destPos:目标数组的起始位置,即复制到目标数组的哪个位置。
  • length:要复制的数组元素的数量。

System.arraycopy() 方法会将源数组中指定位置开始的一定数量的元素复制到目标数组中的指定位置。

以下是一个简单的示例,演示了如何使用 System.arraycopy() 方法复制数组:

public class ArrayCopyExample {
    public static void main(String[] args) {
        int[] sourceArray = {1, 2, 3, 4, 5};
        int[] destinationArray = new int[5];

        System.arraycopy(sourceArray, 0, destinationArray, 0, sourceArray.length);

        for (int i = 0; i < destinationArray.length; i++) {
            System.out.print(destinationArray[i] + " ");
        }
    }
}

以上代码将源数组 sourceArray 复制到目标数组 destinationArray 中,并输出目标数组的内容。输出结果为:1 2 3 4 5

0