2014-03-14 72 views
0

我正在編寫一個有父節點的程序。該父節點有一個2d的字符串數組和包含父節點2d字符串數組但有修改的子節點。但是,當我創建孩子的二維數組時,它會繼續使用對父數組的引用。因此,在兒童創建結束時,父數組會對所有孩子進行修改。我已經嘗試創建一個複製構造函數,使用System.arraycopy,Arrays.copyOf,都無濟於事。 這裏是構造在java中克隆一個2d字符串數組

public class Board 
{ 
private String[][] Gameboard; 
public Board(Board parent) 
{ 
    this.Gameboard = parent.Gameboard; 
} 
} 

我也試圖通過數組循環和分配字符串逐一但也不能工作。 我這樣調用構造函數:

Board temp = new Board(parent); 

回答

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); 
    } 
} 

enter image description here

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())); 
    } 
} 
+0

這次沒工作,它仍然產生了同樣的問題 – user3418488