swap()方法

java

java version "1.8.0_172"
Java(TM) SE Runtime Environment (build 1.8.0_172-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.172-b11, mixed mode)

在Collections类里

/**
 * Swaps the elements at the specified positions in the specified list.
 * (If the specified positions are equal, invoking this method leaves
 * the list unchanged.)
 *
 * @param list The list in which to swap elements.
 * @param i the index of one element to be swapped.
 * @param j the index of the other element to be swapped.
 * @throws IndexOutOfBoundsException if either i or j
 *         is out of range (i < 0 || i >= list.size()
 *         || j < 0 || j >= list.size()).
 * @since 1.4
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public static void swap(List list, int i, int j) {
    // instead of using a raw type here, it's possible to capture
    // the wildcard but it will require a call to a supplementary
    // private method
    final List l = list;
    l.set(i, l.set(j, l.get(i)));
}
List接口

E get(int index);
E set(int index, E element);

 

交换数组里的任意两个元素

temp 变量

/**
 * Swaps the two specified elements in the specified array.
 */
private static void swap(Object[] arr, int i, int j) {
    Object tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

 

 

你可能感兴趣的:(java)