Arrays.copyOf自动创建新数组并可调整大小,适合简化复制和扩容;System.arraycopy需目标数组且性能更高,适用于精细控制和高性能场景。
Java 中 Arrays.copyOf 和 System.arraycopy 都用于数组复制,但它们在使用方式、功能和适用场景上有明显区别。理解这些差异有助于在实际开发中选择更合适的工具。
Arrays.copyOf 是一个静态方法,定义在 java.util.Arrays 类中,用于创建新数组并复制原数组内容。它支持指定新数组长度,可实现扩容或缩容。
示例:T[] Arrays.co
pyOf(T[] original, int newLength)
System.arraycopy 是本地方法,定义在 java.lang.System 类中,用于将源数组的一部分复制到目标数组的指定位置。它要求目标数组必须已存在。
示例:void System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
Arrays.copyOf
System.arraycopy
使用 Arrays.copyOf 的情况:
使用 System.arraycopy 的情况:
Arrays.copyOf 示例:
int[] arr1 = {1, 2, 3};
int[] arr2 = Arrays.copyOf(arr1, 5); // 结果:{1, 2, 3, 0, 0}
System.arraycopy 示例:
int[] src = {1, 2, 3, 4, 5};
int[] dest = new int[5];
System.arraycopy(src, 1, dest, 0, 3); // 将 src[1~3] 复制到 dest[0~2]
// 结果:dest = {2, 3, 4, 0, 0}
基本上就这些。Arrays.copyOf 更方便,适合简单复制和扩容;System.arraycopy 更高效灵活,适合底层操作和性能敏感场景。根据需求选就行。