System arraycopy Overlap Safe Copying

System.arraycopy copies between arrays with overlap handled as if through a temporary buffer, and throws instead of writing when bounds or types do not fit.

JavaData Integrity

Code

snippet
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]);
        }
    }
}

How the snippet works

System arraycopy Overlap Safe Copying reduces to the class ArrayCopyDemo and the function main.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.

Using it

The run emits 3 labeled sections — dest:, overlap:, bounds: — one per step.

Key statements

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

Interactive Tools for This Topic

FAQ

What does System arraycopy Overlap Safe Copying print when run?
The script runs standalone; its 3 labeled outputs include `dest:`, `overlap:`, `bounds:`.