1

The following alters the parameter chr and ends up matching the "swapped" 2D array. I can't see how it can change as it is not on the receiving end of any calculation. There are also similar variables from where this method is called from which are also changed in a similar manner.

private Character[][] moveLeft(Character[][] chr) {
    Character[][] swapped = chr;
    int[] pos = getBlankLocation(chr); //find the blank space

    //location of blank space in 2d array
    int row = pos[0];
    int col = pos[1];
    if (col != 0) {
        Character temp = chr[row][col - 1];
        swapped[row][col - 1] = chr[row][col];            
        swapped[row][col] = temp;

        return swappedChr;
    }
    return null;
}

2 Answers 2

1

You made swapped and chr refer to the same object in memory. Therefore changing one will change the other, since they both reference the same object. Note that this is not the case for primitive values like int.

If you want to swap values in swapped without having an effect in chr, you would need to make a copy or clone of chr. You could do this with a nested for loop that copies values or you could use one of several helper methods.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, an entry for entry copy is the way I went.
1

This is expected. Java is pass-by-value but the value being passed into the method is the memory address of the Array object. Thus the assignment:

Character[][] swapped = chr;

Does not actually create a new array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.