2

I have a State object called state. I am trying to make a clone of it by calling a function applyMoveCloning() which creates a new State object called newState by using a copy constructor.

public State applyMoveCloning(State oldState, Move move) {
    State newState = new State(oldState); // Calls copy constructor
    applyMove(newState, move);            // Calls applyMove() on the newState
    return newState;
}

Here is where I call applyMoveCloning()

State clonedState = game.applyMoveCloning(state, moves.get(i));

The problem is, whenever I make changes to clonedState, it is changing the properties of my old state even though they are different objects (one just has the same properties as the other)

This is my copy constructor

public State(State another) {
    this.width = another.width;  
    this.height = another.height; 
    this.board = another.board; 
}

How can this be happening? It's not like I'm cloning by using State newState = state; so I don't understand.

Brejuro
  • 3,421
  • 8
  • 34
  • 61

1 Answers1

1

Which properties are affected?

Assuming width and height are integers, they are copied by value and not likely to change.

board, on the other hand, looks like a reference and your cloned state is sharing it with the old state.

xiaofeng.li
  • 8,237
  • 2
  • 23
  • 30