比较器主要用于对对象的排序,比如一个对象里面有好几个属性,应该按什么属性规律来排序呢?这就要实现Comparator< E >接口
public class compare {
public static class Student{
String name;
int id;
int age;
public Student(String name,int id,int age) {
this.name=name;
this.id=id;
this.age=age;
}
}
public static class IdAscendComparatr implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.id-o2.id;//升序
//<0 则把前者排进去
//>0 则把后者排进去
//==0 两者相等
}
}
public static class IdDescendComparatr implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o2.id-o1.id;//降序
}
}
public static void PrintStudents(Student[] students) {
for(int i=0;i<students.length;i++) {
System.out.println("name:"+students[i].name+" id:"+students[i].id+" age:"+students[i].age);
}
System.out.println("===============================================");
}
public static void main(String[] args) {
Student t1=new Student("A",2,20);
Student t2=new Student("B",1,18);
Student t3=new Student("C",3,19);
Student[] students= new Student[]{t1,t2,t3};
//Arrays.sort(students);//不知道按什么方式比较,所以出错
//PrintStudents(students);
Arrays.sort(students,new IdAscendComparatr());
PrintStudents(students);
Arrays.sort(students, new IdDescendComparatr());
PrintStudents(students);
//优先队列实际就是堆,比较器也可以用于堆
PriorityQueue<Student> heap=new PriorityQueue<>(new IdDescendComparatr());
heap.add(t1);
heap.add(t2);
heap.add(t3);
while(!heap.isEmpty()) {
Student student=heap.poll();//每次弹出堆顶
System.out.println("name:"+student.name+" id:"+student.id+" age:"+student.age);
}
}
}