是针对集合操作的工具类
常用方法
sort()将列表升序排序
reverse()翻转指定列表的元素
shuffle()使用默认的随机源随机排列指定列表,即洗牌
示例:数字排序什么的没什么好说的,字符串也能排序(跟之前的Comparable有关系)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsTest {
public static void main(String[] args) {
List<String> stringlist=new ArrayList<>();
stringlist.add("abc");
stringlist.add("bca");
stringlist.add("cba");
stringlist.add("acb");
stringlist.add("bac");
stringlist.add("cab");
System.out.println(stringlist);
System.out.println("-----------------------------------");
Collections.sort(stringlist);
System.out.println("sort:"+ stringlist);
System.out.println("-----------------------------------");
Collections.reverse(stringlist);
System.out.println("reverse:"+stringlist);
System.out.println("-----------------------------------");
Collections.shuffle(stringlist);
System.out.println("shuffle:"+stringlist);
}
}
最后做一个案例:按学生年龄排序,年龄相同的按名字排序
Student类,当排序的对象是引用类型的时候它就没法直接排序了,跟之前的TreeSet类似,我采用的是Student类实现Comparable接口
public class Student implements Comparable{
public String name;
public int age;
public Student(String name,int age){
this.name=name;
this.age=age;
}
@Override
public String toString() {
return name+":"+age;
}
@Override
public int compareTo(Object o) {
Student s=(Student) o;
int sum=this.age-s.age;
int result=sum==0?this.name.compareTo(s.name):sum;
return result;
}
}
测试类:测试类代码里我写了另一种比较器的方法(匿名内部类)
public class test {
public static void main(String[] args) {
List<Student> list=new ArrayList<>();
Student student1=new Student("a",16);
Student student2=new Student("b",17);
Student student3=new Student("c",11);
list.add(student1);
list.add(student2);
list.add(student3);
Collections.sort(list);
// Collections.sort(list, new Comparator<Student>() {
// @Override
// public int compare(Student s1, Student s2) {
// int sum=s1.age-s2.age;
// int result=sum==0?s1.name.compareTo(s2.name):sum;
// return result;
// }
// });
for(Student element:list){
System.out.println(element);
}
}
}
结果