我正在通過交換原板上同一行中的兩個相鄰塊來創建一塊新板。問題在於新板覆蓋原板的內容。深度複製多維數組
例如:
int[][] origBoard = { { 0, 4, 6 }, { 5, 3, 1 }, { 2, 8, 7 } };
int[][] twinBoard = { { 0, 6, 4 }, { 5, 3, 1 }, { 2, 8, 7 } };
會發生什麼事是,origBoard變成一樣的twinBoard當我斷言如下:
我的代碼如下:
public class Board {
private int[][] goalBoard;
private final Node node;
private class Node {
private int[][] board;
private int move;
private Node next;
}
// construct a board from an N-by-N array of blocks
// (where blocks[i][j] = block in row i, column j)
public Board(int[][] blocks) {
int N = blocks.length;
goalBoard = new int[N][N];
for (int i = 0; i < dimension(); i++) {
for (int j = 0; j < dimension(); j++) {
if (i == N - 1 && j == N - 1) {
goalBoard[i][j] = 0;
} else {
goalBoard[i][j] = N * i + (j + 1);
}
}
}
// initial node
node = new Node();
node.board = blocks;
node.move = 0;
node.next = null;
}
// board dimension N
public int dimension() {
return goalBoard.length;
}
// a board obtained by exchanging two adjacent blocks in the same row
public Board twin() {
int[][] testBoardATwin = new int[dimension()][dimension()];
testBoardATwin = node.board;
int x = node.board[0][0];
int y = node.board[0][1];
// DEFAULT
if (x != 0 && y != 0) {
testBoardATwin[0][0] = y;
testBoardATwin[0][1] = x;
}
// 2x2
if (dimension() == 2 || y == 0) {
if (x == 0 || y == 0) {
x = node.board[1][0];
y = node.board[1][1];
testBoardATwin[1][1] = x;
testBoardATwin[1][0] = y;
}
} else {
if (x == 0) {
testBoardATwin[0][1] = node.board[0][2];
testBoardATwin[0][2] = y;
}
}
Board board = new Board(testBoardATwin);
return board;
}
// does this board equal y?
public boolean equals(Object y) {
Board testBoard = (Board) y;
if (testBoard == null) {
return false;
}
for (int i = 0; i < dimension(); i++) {
for (int j = 0; j < dimension(); j++) {
if (testBoard.node.board[i][j] != node.board[i][j]) {
return false;
}
}
}
return true;
}
}
我在做什麼錯?請幫忙。 謝謝。
爲什麼不這樣做的原板的內容簡單直接拷貝到新的董事會? – Dai
此外,在Java中,約定是實現'Clonable'接口,並使用名爲'clone'而不是'twin'的方法。 – Dai
在這種情況下,您需要在何處使用物體不可變性? – Lion