Search code examples
javaarraysoopcoding-style

Is it possible to reduce the number of assignment operations in array exchange?


This method has a very simple behavior, as you can see. However, I was wondering if there's a way to simplify this code even further, since it's only doing assignment operations in order to exchange values from the array.

private Board exch(Board a, int i, int j) { // exchange two elements in the array
    int temp = a.board[i];
    a.board[j] = a.board[i];
    a.board[i] = temp;
    return a;
}

Solution

  • Algorithmically there is no better way, but if you are just trying to save lines of coding you can always do this:

    ​import java.util.Collections
    
    //define your array
    
    Collections.swap(arr, i, j);
    

    after this arr will have the values swapped