像这样使用。这是代码的在线编译。看看http://ideone.com/MJJwtc
public static void swap(List list,
int i,
int j)
交换指定列表中指定位置的元素。(如果指定的位置相等,则调用此方法会使列表保持不变。)
参数: list - 交换元素的列表。i - 要交换的一个元素的索引。j - 要交换的另一个元素的索引。
阅读收集的官方文档
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#swap%28java.util.List,%20int,%20int%29
import java.util.*;
import java.lang.*;
class Main {
public static void main(String[] args) throws java.lang.Exception
{
//create an ArrayList object
ArrayList words = new ArrayList();
//Add elements to Arraylist
words.add("A");
words.add("B");
words.add("C");
words.add("D");
words.add("E");
System.out.println("Before swaping, ArrayList contains : " + words);
/*
To swap elements of Java ArrayList use,
static void swap(List list, int firstElement, int secondElement)
method of Collections class. Where firstElement is the index of first
element to be swapped and secondElement is the index of the second element
to be swapped.
If the specified positions are equal, list remains unchanged.
Please note that, this method can throw IndexOutOfBoundsException if
any of the index values is not in range. */
Collections.swap(words, 0, words.size() - 1);
System.out.println("After swaping, ArrayList contains : " + words);
}
}
在线编译示例http://ideone.com/MJJwtc