0

I am having trouble with a 2d array method I have written. It's nothing fancy or complicated. I am developing a Rubik's cube solving program just for fun, and I am still just in the beginning. The problem I am having is that one of the indexes of my 2d array is being reassigned but I am not reassigning it. Here is the code in question:

public static int[][] rightTurn(final int[][] array){
   int[][] newArray = array;
   System.out.println("Array at 02:" + array[0][2]);//this prints 3
   System.out.println("NEW ARRAY:");
   printArray(newArray);//this method just prints each row and column of the array.
   newArray[0][2] = array[1][2];
   newArray[1][2] = array[2][2];
   newArray[2][2] = array[0][2];
   System.out.println("Array at 02:" + array[0][2]);//now it prints 6
   return newArray;
 }

The array I am passing in to this method is

int[][] twoDArray = {{1,2,3},
                     {4,5,6},
                     {7,8,9}
                    };

I have found a way around it by assigning a placeholder variable the value of array[0][2] in my right turn method, then assigning newArray[2][2] = placeholder and that works. But I still don't know why my array is reassigning array[0][2] = 6. Can anyone provide any insight on this?

Randi
  • 91
  • 1
  • 13
  • 2
    You are *not* doing a deep copy of the array based on the line `int[][] newArray = array`. Those arrays point to the same location in memory, and any modifications to `newArray` apply to `array`. – Makoto Oct 05 '16 at 17:12
  • 1
    `int[][] newArray = array` does not create a copy of `array`. It creates a new *reference* to `array`. – John Bollinger Oct 05 '16 at 17:12
  • Wow I feel dumb now. I should have known that. Thank you – Randi Oct 05 '16 at 17:15

0 Answers0