简体   繁体   English

用Java制作对象的副本

[英]Making copies of Objects in Java

I have this Java code: 我有这个Java代码:

boolean[][] defaultBoard = {{false, false, false},
                            {false, false, false},
                            {false, false, false}};
Board board = new Board(defaultBoard);
Board nextBoard = new Board(defaultBoard);
nextBoard.getBoard()[1][5] = true;
board.printBoard();

printBoard : printBoard

public void printBoard() {
    for (boolean row[] : board) {
        for (boolean cell : row) {
            System.out.print( cell ? "#" : "." );
        }
        System.out.println();
    }
    System.out.println();
}

But it returns 但它回来了

...
.#.
...

Which makes me think that nextBoard and board have got the same memory address. 这让我觉得nextBoardboard都有相同的内存地址。 My question is: How do create a copy of nextBoard so that when nextBoard is edited, board isn't edited as well? 我的问题是:如何创建的副本nextBoard这样当nextBoard编辑, board不编辑呢?

It's not board and nextBoard that are the same. 这不是boardnextBoard是相同的。 It is the defaultBoard array you are passing to the constructor. 它是您传递给构造函数的defaultBoard数组。 You need to pass different arrays. 您需要传递不同的数组。 Otherwise, you are just modifying the same array. 否则,您只是修改同一个数组。

Better yet, to ensure instances of Board always contain a new array, I would recommend doing a deep copy of the array inside the constructor. 更好的是,为了确保Board实例始终包含一个新数组,我建议在构造函数中对数组进行深层复制。

An array is an object, so you will pass a reference to the Board constructor. 数组是一个对象,因此您将传递对Board构造函数的引用。 Since you are using the same array, both board and nextBoard are sharing the same object. 由于您使用的是同一个数组,因此boardnextBoard共享同一个对象。 To avoid this situation, use the clone method. 要避免这种情况,请使用clone方法。 This way, you will have a copy of the defaultBoard array and every instance you have their own board. 这样,您将获得defaultBoard数组的副本以及每个具有自己的板的实例。 It will look like this: 它看起来像这样:

Board board = new Board(cloneBoard(defaultBoard));
Board nextBoard = new Board(cloneBoard(defaultBoard));

private boolean[][] cloneBoard(boolean[][] boardToClone) {
    boolean[][] clone = new boolean[boardToClone.length][];
    for(int i = 0; i < boardToClone.length; i++) {
        clone[i] = boardToClone[i].clone();
    }
    return clone;
}

使用.clone()方法,存在于任何Java Object子类中,即所有这些方法,就我所知。

In this case, I would have the board create the array base don a size 在这种情况下,我会让主板创建一个大小的阵列基础

class Board {
    final boolean[] board;

    public Board(int width, height) {
        board = new[width][height];
    }

    public boolean[][] getBoard() { return board; }

    public void set(int x, int y, boolean value) { board[x][y] = value; }
}

Now your code looks like this 现在你的代码看起来像这样

Board board = new Board(3, 3);
Board nextBoard = new Board(3, 3);
nextBoard.set(1, 2, true); // the last element is 2 not 5
board.printBoard();

每次需要将它传递给对象时,您需要创建一个新的新数组,以便对象看到一个新数组,而不是相同的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM