Comparator是比较接口,我们如果需要控制某个类的次序,而该类本身不支持排序(即没有实现Comparable接口),那么我们就可以建立一个“该类的比较器”来进行排序,这个“比较器”只需要实现Comparator接口即可。也就是说,我们可以通过实现 Comparator来新建一个比较器,然后通过这个比较器对类进行排序。
class student {
int studentScore;
String studentName;
public student (String studentName , int studentScore){
this. studentScore = studentScore;
this. studentName = studentName;
}
}
下面以list集合为例:下面的代码是写在另一个类的主方法中
List<student> list = new ArrayList<student>();
list.add(new student ("同学A", 90));
list.add(new student ("同学B", 80));
list.add(new student ("同学C", 90));
list.add(new student ("同学D", 85));
list.add(new student ("同学X", 80));
list.add(new student ("同学M", 75));
list.add(new student ("同学E", 75));
// 在调用sort 方法时创建比较器进行排序
Collections.sort(list, new Comparator< student >() {
@Override
public int compare(student o1, student o2) {
//从小到大排序:o1-o2 ,从大到小排序:o2-o1
if(o1. studentScore!= o2. studentScore){
return o2. studentScore – o1. studentScore;
}else{
return o1. studentName – o2. studentName;
}
}
});
//for循环遍历输出
for (student student: list) {
System.out.println(student. studentName + "\t分数" +
student. studentScore);
}
结果如下:
与Comparable接口相比,Comparator接口不用在要比较的类上实现接口,也不用在类里面实现方法,也就是说不必修改类的源代码,只需要在比较或排序的时候新建一个比较器就行了,然后通过这个比较器对类进行排序。