比较器
实现比较器有两种方法
1 一些类自己实现Comparable,笔试用的较少。
2 人为定义对类的比较。实现Comparator接口。
比较器的应用:
1 快速的对一组数据进行排序,尤其是数据是自己定义的类型时。(如果不使用比较器,默认按内存地址来排序)
2 用于堆结构中(优先级队列)。(如果不使用比较器,默认按内存地址来组织这个堆,没有任何意义)
poll:每次弹出头部(堆顶)
3 用于红黑树。
代码举例
有三个学生 我自创了学术类,main生成了三个学生A、B、C要将他们按照id升序排序,在重写compare方法中,只要return负数,表示第一个数较小,就放前面,程序会自动生成。
1 package basic_class_01; 2 3 import java.util.Arrays; 4 import java.util.Comparator; 5 6 public class Code_09_Comparator { 7 8 public static class Student { 9 public String name; 10 public int id; 11 public int age; 12 13 public Student(String name, int id, int age) { 14 this.name = name; 15 this.id = id; 16 this.age = age; 17 } 18 } 19 20 public static class IdAscendingComparator implements Comparator<Student> { 21 22 @Override 23 public int compare(Student o1, Student o2) { 24 return o1.id - o2.id; 25 } 26 27 } 28 29 public static class IdDescendingComparator implements Comparator<Student> { 30 31 @Override 32 public int compare(Student o1, Student o2) { 33 return o2.id - o1.id; 34 } 35 36 } 37 38 public static class AgeAscendingComparator implements Comparator<Student> { 39 40 @Override 41 public int compare(Student o1, Student o2) { 42 return o1.age - o2.age; 43 } 44 45 } 46 47 public static class AgeDescendingComparator implements Comparator<Student> { 48 49 @Override 50 public int compare(Student o1, Student o2) { 51 return o2.age - o1.age; 52 } 53 54 } 55 56 public static void printStudents(Student[] students) { 57 for (Student student : students) { 58 System.out.println("Name : " + student.name + ", Id : " + student.id + ", Age : " + student.age); 59 } 60 System.out.println("==========================="); 61 } 62 63 public static void main(String[] args) { 64 Student student1 = new Student("A", 1, 23); 65 Student student2 = new Student("B", 2, 21); 66 Student student3 = new Student("C", 3, 22); 67 68 Student[] students = new Student[] { student3, student2, student1 }; 69 printStudents(students); 70 71 Arrays.sort(students, new IdAscendingComparator()); 72 printStudents(students); 73 74 Arrays.sort(students, new IdDescendingComparator()); 75 printStudents(students); 76 77 Arrays.sort(students, new AgeAscendingComparator()); 78 printStudents(students); 79 80 Arrays.sort(students, new AgeDescendingComparator()); 81 printStudents(students); 82 83 } 84 85 }