LeoShwartz
LeoShwartz

Reputation: 21

How can I copy a 2D Array inside an object in Java?

I've defined a class as follows:

Public class Board{
    public static final int SIZE = 4;
    private static char[][] matrix = new char[SIZE][SIZE];

    public Board(){
        clear();//just fills matrix with a dummy character
    }

    public void copy(Board other){//copies that into this
        for(int i = 0; i < SIZE; i++){
            for(int j = 0; j < SIZE; j++){
                matrix[i][j] = other.matrix[i][j];
            }
        }
    }

    //a bunch of other methods
}

So here's my problem: when I try to make a copy, like myBoard.copy(otherBoard), any changes made to one board affect the other. I copied in individual primitive elements, and yet the reference to matrix is the same for both Boards. I thought I was copying elements, why are the pointers the same? What can I do to fix this?

Upvotes: 2

Views: 146

Answers (2)

Paul Boddington
Paul Boddington

Reputation: 37645

Change

private static char[][] matrix = new char[SIZE][SIZE];

to

private char[][] matrix = new char[SIZE][SIZE];

static means that there is only one instance of this array.

Upvotes: 2

Yassin Hajaj
Yassin Hajaj

Reputation: 21975

matrix is static so all the Board objects share the same.

Remove the static to have each Board have its own matrix.

private static char[][] matrix = new char[SIZE][SIZE];   <-- Because of this line
matrix[i][j] = other.matrix[i][j];                       <-- These two are the same.

Upvotes: 5

Related Questions