【发布时间】:2019-12-05 00:09:39
【问题描述】:
我只想将 'clues' 数组复制到 'board' 数组一次。为什么复制一次后线索数组会随着棋盘变化?
public class Ejewbo
{
public static int[][] board = new int[9][9];
public static int[][] clues =
{
{0, 0, 0, 7, 0, 0, 0, 0, 0},
{1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 4, 3, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 6},
{0, 0, 0, 5, 0, 9, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 4, 1, 8},
{0, 0, 0, 0, 8, 1, 0, 0, 0},
{0, 0, 2, 0, 0, 0, 0, 5, 0},
{0, 4, 0, 0, 0, 0, 3, 0, 0},
};
public static void main(String[] args)
{
Ejewbo.board = Ejewbo.clues.clone();
test();
}
public static void printboth()
{
for (int j = 0; j < 9; j++)
{
for (int i = 0; i < 9; i++)
{
System.out.print(Ejewbo.board[j][i]);
System.out.print(" ");
}
System.out.println();
}
System.out.println();
for (int j = 0; j < 9; j++)
{
for (int i = 0; i < 9; i++)
{
System.out.print(Ejewbo.clues[j][i]);
System.out.print(" ");
}
System.out.println();
}
System.out.println("-----");
}
public static void test()
{
for (int i = 0; i < 2; i++) //run twice to see issue
{
Ejewbo.board[0][0]++;
printboth();
}
}
}
我希望线索数组不会改变,但确实如此。当棋盘发生变化时,线索也会发生变化。为什么?有没有更好的方法来复制这样的数组(而不是使用 .clone())?
编辑:第一个答案here 似乎是我复制数组的好方法。
【问题讨论】:
-
您只是在复制外部数组(浅拷贝)。不过,这两个板仍然指向相同的内部数组。你也需要复制那些(深拷贝)。
-
使用我的示例进行深层复制的简单方法是什么?我不明白那篇文章中的解决方案。
-
遍历内部数组并在每个子数组上调用
clone或其他复制方法,然后将副本存储在新的外部数组中。 -
非常感谢,明白了。
标签: java arrays multidimensional-array copy clone