← 中文资源

简体中文版本

System.arraycopy 重叠安全拷贝

System.arraycopy 在同数组重叠时按"先拷临时数组"语义执行、结果正确;越界抛 IndexOutOfBoundsException 且目标不被修改,引用类型转换失败才可能部分写入。

阅读英文原文

实现说明

这个示例的骨架由 ArrayCopyDemo和函数 main构成。

使用要点

  • 跑完文件,输出里会留下标记——dest:、overlap:、bounds:。

常见问题

运行「System.arraycopy 重叠安全拷贝」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 dest:、overlap:、bounds: 标签标明各步骤。

核心语句

System.arraycopy(src, 0, untouched, 1, 3);
System.arraycopy(src, 1, dest, 1, 3);
System.arraycopy(src, 0, src, 2, 3);

代码示例

import java.util.Arrays;

public class ArrayCopyDemo {

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

        // 基本用法:src 的 2..4 拷到 dest 的 1..3
        int[] dest = {0, 0, 0, 0, 0};
        System.arraycopy(src, 1, dest, 1, 3);
        System.out.println("dest: " + Arrays.toString(dest));

        // 同数组重叠:srcPos < destPos 时若按顺序原地写会踩坏数据,
        // arraycopy 保证"如同先拷到临时数组"的语义,结果正确
        System.arraycopy(src, 0, src, 2, 3);
        System.out.println("overlap: " + Arrays.toString(src));

        // 越界抛 IndexOutOfBoundsException,且目标数组不被修改
        int[] untouched = {9, 9, 9};
        try {
            System.arraycopy(src, 0, untouched, 1, 3);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("bounds: " + untouched[0] + untouched[1] + untouched[2]);
        }
    }
}