1

Hi so I'm relatively new to programming so this might be a silly question.

So I have these lines of code in a run function:

int[] bstate = this.state;
System.out.println(Arrays.toString(bstate));

nextMove();

int[] astate = this.state;
System.out.println(Arrays.toString(astate));
System.out.println(Arrays.toString(bstate));

to check whether or not nextMove() had changed the state of the object, but I think when state was updated, bstate was updated too because after the method call, bstate was the same as astate where it wasn't before.

So I'm wondering if as my methods update state, they implicitly update bstate too and if so, how do I prevent this from happening?

Isaac lee
  • 23
  • 3

2 Answers2

4

= just assigns a reference to arrays. It doesn't copy them.

The fix is to call clone() on the array. It's a shallow copy, so would have strange behaviour for, say, int[][] or StringBuilder[].

int[] bstate = this.state.clone();
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
1

Anything other than primitive types assigns a reference. int[] is actually an object. Another poster recommended cloning, ditto.

mcmaillet
  • 11
  • 1