Java Array Swap swap(T[] arr, int a, int b)

Here you can find the source of swap(T[] arr, int a, int b)

Description

Swaps the elements at position a and b in the array arr.

License

Open Source License

Parameter

Parameter Description
T Type of array elements
arr Array that contains the elements to be swapped
a First position
b Second position

Declaration

public static <T> void swap(T[] arr, int a, int b) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//from   w w  w . ja  v  a  2  s. c om
     * Swaps the elements at position <code>a</code> and <code>b</code> in the
     * array <code>arr</code>.
     * 
     * @param <T>
     *            Type of array elements
     * @param arr
     *            Array that contains the elements to be swapped
     * @param a
     *            First position
     * @param b
     *            Second position
     */
    public static <T> void swap(T[] arr, int a, int b) {
        if (a < 0 || a > arr.length || b < 0 || b > arr.length)
            throw new IllegalArgumentException("swap position out of bounds.");
        if (a != b) {
            T t = arr[a];
            arr[a] = arr[b];
            arr[b] = t;
        }
    }
}

Related

  1. swap(short x[], T[] a2, int a, int b)
  2. swap(short[] array, int indexA, int indexB)
  3. swap(String a[], int i, int j)
  4. swap(T[] a, int i1, int i2)
  5. swap(T[] a, int idx1, int idx2)
  6. swap(T[] arr, int i, int j)
  7. swap(T[] arr, int index1, int index2)
  8. swap(T[] arr, int pos1, int pos2)
  9. swap(T[] array, int a, int b)