Swap array elements

Java does not have any direct method to swap array elements. We have to create function like following. For primitive type array we have to create individual function for each type. Consider following function which swap elements in int array.

public void swap(int[] arr, int index1, int index2) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;

Here we have to introduce one temporary variable to perform swap. But for array of wrapper classes we can create generic function for swapping. Following program illustrates the generic function for swapping elements of any Object array.

public <T> void swap(T[] arr, int index1, int index2) {
    T temp = arr[index1];
    arr[index1] = arr[index2];
    arr[index2] = temp;

As above function should have checks to disallow operation for null array and for negative index value. Otherwise caller of the method may face IndexOutOfBoundsException or NullPointerException. Moreover, we can use Collections.swap(list, index1, index2) for swapping elements of list, if we can convert our array to list.

Following function will swap the elements with swap method of Collections. But it has extra overhead of converting array to list and then list to array.

public <T> void swap(T[] arr, int index1, int index2) {
    List<T> list = Arrays.asList(arr);
    Collections.swap(list, index1, index2);
    arr = (T[]) list.toArray();// Raise unchecked casting warning