System.arraycopy 用法

System.arraycopy 是 Java 中一个非常实用的方法,用于高效地复制数组的部分或全部内容。它的语法如下:

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

参数说明:

  • src: 源数组,即要复制的数据来源。
  • srcPos: 源数组中开始复制的起始位置(索引)。
  • dest: 目标数组,即数据要复制到的数组。
  • destPos: 目标数组中开始插入的起始位置(索引)。
  • length: 要复制的元素数量。

示例用法:

以下是一些使用 System.arraycopy 的示例:

示例 1:基本的数组复制

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 num : destinationArray) {
            System.out.print(num + " "); // 输出: 1 2 3 4 5
        }
    }
}

示例 2:复制数组的一部分

public class PartialArrayCopyExample {
    public static void main(String[] args) {
        String[] sourceArray = {"A", "B", "C", "D", "E"};
        String[] destinationArray = new String[3];

        // 从源数组复制部分内容
        System.arraycopy(sourceArray, 1, destinationArray, 0, 3);

        // 打印目标数组
        for (String letter : destinationArray) {
            System.out.print(letter + " "); // 输出: B C D
        }
    }
}

示例 3:处理重叠区域

如果源数组和目标数组重叠,System.arraycopy 将正确处理这种情况。例如:

public class OverlappingArrayCopyExample {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};

        // 将数组的前两个元素移动到后面
        System.arraycopy(array, 0, array, 2, 3);

        // 打印修改后的数组
        for (int num : array) {
            System.out.print(num + " "); // 输出: 1 2 1 2 3
        }
    }
}

注意事项:

  1. 如果源数组和目标数组的类型不匹配,程序会抛出 ArrayStoreException
  2. 如果复制的长度超出了源数组或目标数组的边界,会抛出 ArrayIndexOutOfBoundsException
  3. 使用 System.arraycopy 通常比手动循环复制数组更高效,因为它是由 Java 虚拟机专门优化的。

通过这些示例和说明,希望能帮助您更好地理解 System.arraycopy 的用法!

posted @ 2026-01-13 10:03  盘思动  阅读(23)  评论(0)    收藏  举报