比较器的应用

154 阅读1分钟

对于数的比较我们可以用sort直接排好,但是如果是我们自己定义的结构怎样比大小呢,这就要用到比较器了。例如下面我们可以对Student来排序:

    public static void main(String[] args) {
        Student student1 = new Student("A", 2, 20);
        Student student2 = new Student("B", 3, 21);
        Student student3 = new Student("C", 1, 22);
        Student[] students = new Student[]{student1, student2, student3};
        Arrays.sort(students,new IdAscendingComparator());
        printStudents(students);
        System.out.println("============");
        //由于优先级队列默认是小根堆形式,要是大根堆的话,就需要比较器的应用。这个题因为是特殊结构所以一定要用比较器。
        PriorityQueue<Student> maxHeapBasedAge = new PriorityQueue<>(new AgeDescendingComparator());
        maxHeapBasedAge.add(student1);
        maxHeapBasedAge.add(student2);
        maxHeapBasedAge.add(student3);
        while (!maxHeapBasedAge.isEmpty()){
            Student student = maxHeapBasedAge.poll();
            System.out.println("Name: " + student.name + ", Id : " + student.id + ", Age : " + student.age);
        }
    }

    public static void printStudents(Student[] students) {
        for (Student student : students){
            System.out.println("Name: " + student.name + ", Id: " + student.id + ", Age: " + student.age);
        }
    }

    public static class Student{
        public String name;
        public int id;
        public int age;
        public Student(String name, int id, int age){
            this.name = name;
            this.id = id;
            this.age = age;
        }
    }
    //对Student的id进行排序,运用比较器,实现Comparator接口,重写compare方法
    public static class IdAscendingComparator implements Comparator<Student> {
        @Override
        // 比较器的默认原则
        // 返回负数的时候,第一个参数排在前面
        // 返回正数的时候,第二个参数排在前面
        // 返回0的时候,谁在前面无所谓
        public int compare(Student o1, Student o2) {
            //比如我们想以Student的id进行升序排序
            //if(o1.id < o2.id){
            //    return -1;//保证o1放前面
            //}
            //if(o1.id > o2.id){
            //    return 1;//保证o2放前面
            //}
            //return 0;
            //故上面的整体代码可以写成:
            return  o1.id - o2.id;//可以简记为升序是前 - 后,降序为后 - 前
        }
    }

    public static class AgeDescendingComparator implements Comparator<Student> {
        @Override
        public int compare(Student o1, Student o2) {
            return  o2.age - o1.age;//可以简记为升序是前 - 后,降序为后 - 前
        }
    }

比较器总结:

  1. 比较器的实质就是重载比较运算符
  2. 比较器可以很好的应用在特殊标准的排序上,如自定义类型
  3. 比较器可以很好的应用在根据特殊标准排序的结构上,如堆