0

I have the following in my program:

 public static GameBoard possibleStates(GameBoard GameState, int turn)
    {
        printGameBoard(GameState); //getting what is passed in here
        int innerCounter = 0;
        int outerCounter = 0;
        while(outerCounter < 3)
        {
            while(innerCounter < 3)
            {
                if(GameState.Board[outerCounter][innerCounter].isEmpty())
                {
                    GameBoard PossibleBoard = new GameBoard();
                    PossibleBoard.Copy(GameState);
                    PossibleBoard.Board[outerCounter][innerCounter].ModifyOccupy(move); //the problem is here, changes to possibleboard are also reflected in gamestate
                    GameState.AddToActions(PossibleBoard);
                }
                innerCounter++;
            }
            innerCounter = 0;
            outerCounter++;
        }
        return GameState;
    }

My problem is that changing one, alters the value of another. I know it's because they are referencing the same space in memory, I just can't figure out how to not make them do that. I have already tried using the Copy method, and Clone method for my GameBoard class and they have not made any difference.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
bkoenig
  • 45
  • 7
  • Show your `Copy` method. That's probably where the problem lies – k_g Mar 07 '15 at 00:36
  • 1
    First of all, you should to take a quick look about naming conventions, variables a methods names should start with lowercase letters: http://www.oracle.com/technetwork/java/codeconventions-135099.html – Tarik Mar 07 '15 at 00:38

1 Answers1

1

Inside copy method where you are actually creating the copy, you need to create a deep copy. That is copying the references is not enough, rather you will need to create new objects and initialize them with the state of the original object.

Only then it will be a completely independent object and will not change the original object.

This might be a helpful detail

What is the difference between a deep copy and a shallow copy?

Community
  • 1
  • 1
muasif80
  • 5,586
  • 4
  • 32
  • 45