1. 程式人生 > 其它 >Java物件排序之比較器(陣列中的物件排序,堆中的物件排序(優先順序佇列),紅黑樹中的物件排序)

Java物件排序之比較器(陣列中的物件排序,堆中的物件排序(優先順序佇列),紅黑樹中的物件排序)

技術標籤:#資料結構演算法學習比較器comparatorjava物件排序優先順序佇列

Java中的比較器,就是Comparator介面,實現這個介面,並實現compara方法,就能實現比較器。

比較器的作用:
通常的排序演算法一般都是對基本資料型別排序,比如整數浮點數等,但是,如果需要排序的是個物件呢?現在需要根據物件中的某個屬性進行排序,怎麼實現?這就需要比較器了。

比較器例子:
舉個例子,現在有一個學生物件,學生物件中有姓名、年齡、學號三個屬性,現在有一個學生物件的陣列,想要對陣列中的學生進行排序,根據年齡升序排序。
實現Comparator介面並重寫compara方法,在compara方法中,如果返回值是負數,就是升序排序;如果返回值是正數,就是降序排序;如果是0,就是兩個一樣大。

public static void main(String[] args) {

        Student s1=new Student("學生1",10,1);
        Student s2=new Student("學生2",12,2);
        Student s3=new Student("學生3",8,3);

        Student[] students=new Student[]{s1,s2,s3};
        Arrays.sort(students,new MyComparator
()); for (Student s : students) { System.out.println(s.name); } } public static class MyComparator implements Comparator<Student>{ public int compare(Student o1, Student o2) { return o1.age-o2.age; } } public static class Student{ public
Student(String name, int age, int num) { this.name = name; this.age = age; this.num = num; } private String name; private int age; private int num; }

Java中利用比較器對陣列中物件的排序:

Arrays.sort(students, new Comparator<Student>() {
            public int compare(Student o1, Student o2) {
                return o1.age-o2.age;
       }
});

Java中利用比較器對優先順序佇列中的物件進行排序:優先順序佇列底層就是堆排序,其實就是Java幫你寫的堆排序演算法。比較器返回負數對應的是小根堆,返回正數對應大根堆:

PriorityQueue<Student> heap = new PriorityQueue<Student>(new Comparator<Student>() {
            public int compare(Student o1, Student o2) {
                return o1.num- o2.num;
      }
});

Java中利用比較器對紅黑樹中物件的排序:

TreeSet<Student> treeSet=new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.age-o2.age;
            }
        });