Java Collections.swap()方法解析
jdk源码:
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,i(下标①),j(下标②)
-
list
:在该列表中的调剂元素。 -
i
: 要交换的一个元素的索引。 -
j
: 要交换的其它元素的索引。
作用
:将传入的list中的下标为i和下标为j的元素交换(乾坤大挪移神功)。
实例解析:
List l = new ArrayList();
l.add(1);
l.add(2);
l.add(3);
Collections.swap(l, 0, 2);
此时的l中的元素就被交换了,顺序由原来的1 2 3,变为新的3,2,1