Search code examples
javaarraysmultidimensional-arrayswap

Swap two elements in a 2D array


I write this method for swapping two elements in a 2D array:

    public void swap(Object[][] array, int a, int b) {
    Object temp;
    temp = array[a];
    array[a] = array[b];
    array[b] = temp; // Error, Why?
}

But there is a compile time error in last line.

For example, i want to swap array[i][j+1] and array[i+1][j] elements, How should call this method?

(i and j are int in for loop)

update

Should i swap by element-based ? Or by index-based?

How should be my parameters in swap array?

Update 2

    public void swap(Object[][] array, int i1, int j1, int i2, int j2) {
    Object tempObject = array[i1][j1];
    array[i1][j1] = array[i2][j2];
    array[i2][j2] = tempObject;
}

Is this correct for swapping arbitrary elements of a 2D array?


Solution

  • You are using a and b as only one coordinate each into a 2D array, so array[a] and array[b] refer to the arrays representing the rows a and b, not the individual elements.

    The error arises when you attempt to assign an Object to an Object[] (array[b]) on your last line.

    Use both a and b as your i and j explanation indicates.

    Object temp = array[a][b + 1];
    array[a][b + 1] = array[a + 1][b];
    array[a + 1][b] = temp;