Sajad
Sajad

Reputation: 2363

Swap a 2-D array rows

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?

Upvotes: 1

Views: 106

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

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;
}

Upvotes: 4

Related Questions