Can I swap two int[] using swap function in java?

2019-09-15 19:18发布

问题:

I created a 2D array of int[] Now, I want to swap two int[] inside of 2D array

I have this for my code:

swap(values[row][col], values[randomRow][randomCol]); 

where values is a 2D array of int[]. so values[int][int] is a int[];

I get an error message like this:

Error: The method swap(int[], int[]) is undefined for the type ShufflePic

How should I fix this?

Thanks a lot!

回答1:

Java is pass-by-value. You cannot swap values like this.

Instead use this approach :

void swap(int[][] array, int row1, int col1, int row2, int col2) {
    int temp = array[row1][col1];
    array[row1][col1] = array[row2][col2];
    array[row2][col2] = temp;
}

Now you can call swap(...) method to swap the values

swap(values, row, col, randomRow, randomCol);


回答2:

mybe your method should looks like

swap(int[] arryFirst, int arryFirstRow, int arryFirstCol, int[] arrySec, int arrySecRow, int arrySecCol)


回答3:

Basically, this finds the indices and swaps according to these indices. Try printing the items in the list after swapping. Of course, this technique could also be implemented for 2D arrays, but I'll leave that as a challenge for you.

 public class Test {
    static int[] list = {4, 5, 6, 3, 1, 2};

    public static void main(String[] args) {
        swap(6, 2); // test swap
    }

    public static void swap(int a, int b) {
        int a_index = 0;
        int b_index = 0;

        for (int i = 0; i < list.length; i++) {
            if (list[i] == a) a_index = i;
            if (list[i] == b) b_index = i;
        }

        list[a_index] = b;
        list[b_index] = a;
    }
}


回答4:

I created a 2D array of int[]

You did indeed do that, but you probably wanted to create a 2D array of int, not int[].

values[row][col] = 5 //2d int array
values[row][col] = new int[length] //3d int array. Probably not what you intended

Once you fix that, the other answers about passing by value should work for you.

EDIT: If that's what you want, then this method should work:

public void swapArrays(int[][][] arr, int row1, int col1, int row2, int col2) {
    int[] temp = arr[row1][col1];
    arr[row1][col1] = arr[row2][col2];
    arr[row2][col2] = temp;
}

You would then call this with:

swapArrays(values, row, col, randomRow, randomCol);

The reason you were getting the error is because you hadn't defined a swap function which takes in two arrays. However, even if you had, it wouldn't have functioned properly because of the pass-by-value, pass-by-reference thing. (Google it for more info on that.)

With my proposed method, it will have a reference to the entire array, enabling it to change its values. If you just passed in values[row][col], the method would only see the value stored at that index, but not access to the values array.