我正在编写一个有父节点的程序。该父节点具有2d String数组和子节点,其中包含父节点2d String数组但具有修改。但是,当我创建子级的2d数组时,它会继续使用对parents数组的引用。因此,在子项创建结束时,父数组具有所有子项的修改。我尝试使用System.arraycopy,Arrays.copyOf创建一个复制构造函数,但都无济于事。 这是构造函数
public class Board
{
private String[][] Gameboard;
public Board(Board parent)
{
this.Gameboard = parent.Gameboard;
}
}
我也试过循环遍历数组并逐个分配字符串,但这也不起作用。 我像这样调用构造函数:
Board temp = new Board(parent);
答案 0 :(得分:0)
试试这个:
class parent {
static String[][] Gameboard = new String[5][5];
public static void main (String[] args) {
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
Gameboard[i][j] = "" + j;
}
}
Board b = new Board();
}
}
class Board {
private String[][] Gameboard;
public Board() {
this.Gameboard = parent.Gameboard;
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
System.out.print("" + this.Gameboard[i][j]);
}
System.out.print("\n");
}
System.out.print("Lenght Of Class Boar.GameBoard =" + this.Gameboard.length);
}
}
答案 1 :(得分:0)
您可以使用复制构造函数,如下例所示:
public class Test {
String[][] arr2D = new String[2][2];
public Test() {
}
public Test(Test t) {
this.arr2D = deepCopy(t.arr2D);
}
// deepCopy
private String[][] deepCopy(String[][] arr2D) {
String[][] arr2D2 = new String[arr2D.length][arr2D.length];
for (int i = 0; i < arr2D.length; i++) {
for (int j = 0; j < arr2D.length; j++) {
arr2D2[i][j] = arr2D[i][j];
}
}
return arr2D2;
}
public void setArr2D(String[][] arr2D) {
for (int i = 0; i < arr2D.length; i++) {
for (int j = 0; j < arr2D.length; j++) {
arr2D[i][j] = i + "row " + j + "column";
}
}
}
public String[][] getArr2D() {
return this.arr2D;
}
public static void main(String[] args) {
Test t1 = new Test();
t1.setArr2D(t1.getArr2D());
System.out.println(Arrays.deepToString(t1.getArr2D()));
Test t2 = new Test(t1);
t2.setArr2D(t1.getArr2D());
System.out.println(Arrays.deepToString(t2.getArr2D()));
}
}