java如何复制数组
使用System.arraycopy方法
System.arraycopy是Java中高效复制数组的方法,适用于任意类型的数组。需要指定源数组、源起始位置、目标数组、目标起始位置及复制长度。
int[] source = {1, 2, 3, 4, 5};
int[] destination = new int[5];
System.arraycopy(source, 0, destination, 0, source.length);
- 参数说明:源数组、源起始索引、目标数组、目标起始索引、复制的元素数量。
- 注意:需确保目标数组长度足够,否则抛出
ArrayIndexOutOfBoundsException。
使用Arrays.copyOf方法
适用于创建新数组并复制内容,可截断或填充默认值。
int[] original = {1, 2, 3};
int[] copied = Arrays.copyOf(original, original.length); // 完整复制
int[] truncated = Arrays.copyOf(original, 2); // 截断为前2个元素
int[] extended = Arrays.copyOf(original, 5); // 扩展长度,多余元素填充0
- 适用于一维数组,底层调用
System.arraycopy。 - 第二个参数为新数组长度,可大于或小于原数组长度。
使用clone方法
数组本身实现了Cloneable接口,直接调用clone()可浅拷贝数组。
int[] array = {1, 2, 3};
int[] clonedArray = array.clone();
- 简单易用,但仅适用于一维数组的浅拷贝。
- 多维数组的复制仍需遍历或使用其他方法。
手动遍历复制
通过循环逐元素复制,灵活但代码量较多。
int[] source = {1, 2, 3};
int[] destination = new int[source.length];
for (int i = 0; i < source.length; i++) {
destination[i] = source[i];
}
- 适用于需要特殊处理的场景(如条件过滤)。
- 性能低于
System.arraycopy。
多维数组复制
多维数组需逐层复制,或结合上述方法嵌套使用。
int[][] matrix = {{1, 2}, {3, 4}};
int[][] copiedMatrix = new int[matrix.length][];
for (int i = 0; i < matrix.length; i++) {
copiedMatrix[i] = Arrays.copyOf(matrix[i], matrix[i].length);
}
- 注意:直接使用
clone()或Arrays.copyOf对多维数组仅是浅拷贝。
第三方库(如Apache Commons Lang)
使用ArrayUtils.clone或ArrayUtils.addAll简化操作。
import org.apache.commons.lang3.ArrayUtils;
int[] array = {1, 2, 3};
int[] copied = ArrayUtils.clone(array);
- 需添加依赖,适合项目中已使用该库的场景。
选择建议
- 性能优先:
System.arraycopy。 - 简洁性:
Arrays.copyOf或clone()。 - 复杂需求:手动遍历或第三方库。







