可以操作Set、List和Map等集合的工具类,里面提供了一系列静态方法对集合元素进行查询、排序和修改等操作。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Collections_01 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("Tom");
arrayList.add("Mary");
arrayList.add("Amy");
arrayList.add("Jack");
Collections.reverse(arrayList);//反转List中元素的顺序
System.out.println(arrayList);
Collections.shuffle(arrayList);//对list元素随机打乱
System.out.println(arrayList);
Collections.sort(arrayList);//根据元素的自然顺序对指定List集合元素按升序排序
System.out.println(arrayList);
Collections.sort(arrayList, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return 0;//重写compare方法,则可按照指定的方法进行排序。
}
});
//swap(List,int i,int j)指定list集合中i处的元素与j处的元素交换位置
Collections.swap(arrayList,1,3);
System.out.println(arrayList);
}
}
[Jack, Amy, Mary, Tom]
[Mary, Tom, Amy, Jack]
[Amy, Jack, Mary, Tom]
[Amy, Tom, Mary, Jack]
Process finished with exit code 0
import java.util.ArrayList;
import java.util.Collections;
public class Collections_02 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add("Tom");
arrayList.add("Mary");
arrayList.add("Amy");
arrayList.add("Jack");
arrayList.add("Amy");
System.out.println(Collections.max(arrayList));//根据元素的自然顺序,返回给定集合中的最大值
System.out.println(Collections.frequency(arrayList,"Amy"));//查看Amy在集合中出现的次数
ArrayList arrayList1 = new ArrayList();
arrayList1.add("123");
arrayList1.add("456");
Collections.copy(arrayList,arrayList1);//将arrayList1中的内容拷贝到arrayList中
System.out.println(arrayList);
}
}
Tom
2
[123, 456, Amy, Jack, Amy]
Process finished with exit code 0