Jona
Jona

Reputation: 1061

What is causing the change in my 2D array?

I have a 2D array called "playingField". Before any alterations take place, I make a tempField 2D array and set tempField = playingField.

After several modifications, which all work, I get to this point in the code:

else {
//at this point both playingField and tempField are unchanged still
    boundsNormal = bounds.OutOfBounds(move.MovePlayer(playingField,trekker, direction, rowT, colT));
    if(boundsNormal == true){
//for some reason, at this point, tempField gets reassigned to the new playingField (which I'm still not sure why *THAT* changes)
        playingField = tempField;

MovePlayer is a method that modifies the 2D array it takes (in this case, playingField), and OutOfBounds returns true or false, given an array.

I can maybe understand why playingField is being changed, but have no idea why tempField should experience any alteration after I initialize the boundsNormal variable.

Upvotes: 0

Views: 78

Answers (2)

3yakuya
3yakuya

Reputation: 2662

playingField = tempField;

This line of code does not copy your array, it copies the reference. After this assignment both playingField and tempField represent the same array in the memory (the array represented by playingField before this is probably waiting to be garbage collected.) Therefore, if after this you change anything in the array represented by playingField, the changes will also be visible in tempField, as it is basically the same array now (not copied array, just the same array with two names).

Upvotes: 0

Robin Green
Robin Green

Reputation: 33033

I make a tempField 2D array and set tempField = playingField.

What you're saying doesn't make sense. You're making an array variable called tempField, but if you do

tempField = playingField

then both variables now point to the same array. So they are both being changed because they are the same array.

To avoid this, you can generally use System.arrayCopy instead of =. However, for a 2-dimensional array it's a little more complicated to "deep copy" it, because you have an array of arrays.

(Note: More generally, when objects are mutable, you may need to "deep copy" or "deep clone" them instead of use =, to avoid this problem. Arrays are just one example of this general rule.)

Upvotes: 2

Related Questions