参见英文答案 > How do I do a deep copy of a 2d array in Java?????????????????????????????????????6个
编辑2:下面是一个基于DuffyMo响应的代码片段,演示了如何使用System.arraycopy克服多维数组克隆的局限性.
import java.util.Arrays;
public class Randar {
public static int[][] arrayMaster = {{6,1}, {10,1}, {1,1}};
private static int[][] arrayChanges = new int[arrayMaster.length][2];
public Randar () {
}
public static void main(String[] args) {
arrayChanges[0][0] = 0;
resetArrays(arrayChanges, arrayMaster);
arrayChanges[0][0] = 0;
System.out.format("arrayMaster: %s, arrayChanges: %s", Arrays.deepToString(arrayMaster), Arrays.deepToString(arrayChanges));
}
public static void resetArrays(int[][] arrayChanges, int[][] arrayMaster) {
for (int a=0; a< arrayMaster.length; a++) {
System.arraycopy(arrayMaster[a], 0, arrayChanges[a], 0, arrayMaster[a].length);
}
// arrayChanges = arrayMaster.clone(); will NOT work as expected
}
}
[原始问题]
在Java中(完全)克隆多维数组的简单方法是什么?这个程序说明了我的问题.
import java.util.Arrays;
public class Randar {
public static int[][] arrayMaster = {{6,1}, {10,1}, {1,1}};
static private int[][] arrayChanges = arrayMaster;
public static void main(String[] args) {
arrayChanges[0][0] = 0;
resetArrays();
System.out.format("arrayMaster: %s, arrayChanges: %s",Arrays.deepToString(arrayMaster), Arrays.deepToString(arrayChanges));
}
public static void resetArrays() {
arrayChanges = arrayMaster.clone();
}
}
运行上面的代码时,arrayMaster和arrayChanges一样会改变,这与我的意图相反.认为我可以克隆arrayMaster的每个单维数组成员,我试图解决这个问题:
for (int iter = 0; iter < arrayMaster.length; iter++) {
arrayChanges[iter] = arrayMaster[iter].clone();
}
但是当我运行由于某种原因而给出NullPointerException的代码时.编写一个循环遍历数组的各个整数值的方法是我唯一的选择吗?
谢谢.
编辑1:这也不能解决问题.
import java.util.Arrays;
public class Randar {
public int[][] arrayMaster = {{6,1}, {10,1}, {1,1}};
private int[][] arrayChanges = arrayMaster.clone();
public Randar () {
}
public static void main(String[] args) {
Randar Randar1 = new Randar();
Randar1.arrayChanges[0][0] = 0;
resetArrays(Randar1.arrayChanges, Randar1.arrayMaster);
Randar1.arrayChanges[0][0] = 0;
System.out.format("arrayMaster: %s, arrayChanges: %s", Arrays.deepToString(Randar1.arrayMaster), Arrays.deepToString(Randar1.arrayChanges));
}
public static void resetArrays(int[][] arrayChanges, int[][] arrayMaster) {
/*for (int a=0; a< arrayMaster.length; a++) {
System.arraycopy(arrayMaster[a].clone(), 0, arrayChanges[a], 0, arrayMaster[a].length);
} */
arrayChanges = arrayMaster.clone();
}
}