1

I use this code for swap a 2-d array rows (A and B):

public static void swapRows(int[][] array, int[] rowA, int[] rowB) {
    int[] tempRow;
    tempRow = rowA;
    rowA = rowB;
    rowB = tempRow;
}

But after call this method and displayed array, It not changed at all!

Why?

Sajad
  • 2,016
  • 10
  • 44
  • 81
  • It doesn't look like your are changing anything to me. Where are you putting each row into the temp rows and rowA and rowB? You should try printing out the contents of the rows. Also, this could be done using for loops. – David MacNeil Apr 11 '14 at 17:39
  • This might be useful reading, http://stackoverflow.com/questions/40480/is-java-pass-by-reference, it'll help you understand how arguments are passed in java. – Martin Apr 11 '14 at 17:43

1 Answers1

4

This is because you are swapping references, which are passed by value (I know, this sounds confusing, but that is what Java does). When you do this assignment

rowA = rowB;

the effect of the change is visible inside your function, not outside it. In order for the effects to be visible by the caller, you need to operate on the array object.

Here is how: first, change the API to take indexes rather than the actual rows. Then change the code to use these indexes into the 2D array, like this:

public static void swapRows(int[][] array, int rowA, int rowB) {
    int[] tempRow = array[rowA];
    array[rowA] = array[rowB];
    array[rowB] = tempRow;
}
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399