开发者

2D array values are getting changed without explicitly declaring them in Java

开发者 https://www.devze.com 2023-02-14 10:46 出处:网络
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.

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 t开发者_C百科his 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;
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号