目录
1.先来源码:
2.测试过程如下:
集合交换元素使用Collections.swap(List> list, int i, int j);
1.先来源码:
逻辑比较简单,注意 l.set(j, l.get(i)) 方法返回的是集合该位置原来的值。
/**
* 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)));
}
2.测试过程如下:
import java.util.ArrayList;
import java.util.Collections;
public class SwapDemo {
public static void main(String[] args) {
ArrayListlist = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list);
Collections.swap(list, 0, 1);
System.out.println(list);
}
}
输入结果如下:可以看到前两个元素的位置已完成交换。
[1, 2, 3]
[2, 1, 3]
Process finished with exit code 0