1

I have this Java code:

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:

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. My question is: How do create a copy of nextBoard so that when nextBoard is edited, board isn't edited as well?

awsomeguy
  • 191
  • 3
  • 11

5 Answers5

4

It's not board and nextBoard that are the same. It is the defaultBoard array you are passing to the constructor. 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.

Joe F
  • 4,174
  • 1
  • 14
  • 13
  • 4
    if `Board`'s constructor made a defensive copy of its input, then it would be harder to write a misbehaving client. – Mike Samuel May 11 '13 at 21:02
0

An array is an object, so you will pass a reference to the Board constructor. Since you are using the same array, both board and nextBoard are sharing the same object. To avoid this situation, use the clone method. This way, you will have a copy of the defaultBoard array and every instance you have their own board. 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;
}
Daniel Pereira
  • 2,720
  • 2
  • 28
  • 40
0

Use the .clone() method, present in any Java Object subclass, namely, all of them, far as I can tell.

hd1
  • 33,938
  • 5
  • 80
  • 91
0

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();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You need to create a new fresh array every time you need to pass it to object so that the object's see a new array rather then the same array .

csk
  • 566
  • 1
  • 5
  • 15