package com.cisco.www.sort;import java.util.Arrays;import java.util.PriorityQueue;import java.util.TreeMap;import java.util.TreeSet;/** * 比较器:负数第一个参数放前面,正数第二个参数放前面,相等则二者是相等的 */public class Comparator { 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; } } public static class IdAscendingComparator implements java.util.Comparator<Student>{ @Override public int compare(Student o1, Student o2) { //返回负数,则前面的值更小(按照升序),否则后面的值小(按照降序)。 return o1.id-o2.id; } } //比较器:负数第一个参数放前面,正数第二个参数放前面,相等则二者是相等的 public static class IdDescendingComparator implements java.util.Comparator<Student>{ @Override public int compare(Student o1, Student o2) { return o2.id-o1.id; } } public static class AgeAscendingComparator implements java.util.Comparator<Student>{ @Override public int compare(Student o1, Student o2) { //返回负数,则前面的值更小(按照升序),否则后面的值小(按照降序)。 return o1.age-o2.age; } } //比较器:负数第一个参数放前面,正数第二个参数放前面,相等则二者是相等的 public static class AgeDescendingComparator implements java.util.Comparator<Student>{ @Override public int compare(Student o1, Student o2) { return o2.age-o1.age; } } public static class MyComp implements java.util.Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } } public static void main(String[] args){ Student student1 = new Student("A",1,23); Student student2 = new Student("B",2,21); Student student3 = new Student("C",3,22); //创建Student数组,将student都放进去 Student[] students =new Student[]{student3,student2,student1}; printStudents(students); Arrays.sort(students,new IdAscendingComparator()); printStudents(students); Arrays.sort(students,new IdDescendingComparator()); printStudents(students); Arrays.sort(students,new AgeAscendingComparator()); printStudents(students); Arrays.sort(students,new AgeDescendingComparator()); printStudents(students); Integer[] arr= {3,2,4,1,0}; Arrays.sort(arr,new MyComp()); printArray(arr); //优先级队列就是堆,如果什么参数都不提供,那么默认按照内存地址来组织这个堆 PriorityQueue<Student> heap = new PriorityQueue<>(new IdAscendingComparator()); heap.add(student3); heap.add(student2); heap.add(student1); while (!heap.isEmpty()){ //每次弹出堆的堆顶,然后将堆的大小减1 Student student = heap.poll(); System.out.println("Name:"+student.name+",Id:"+student.id+",Age:"+student.age); } //红黑树 TreeSet<Student> treeSet = new TreeSet<>(new IdAscendingComparator()); //........... } public static void printStudents(Student[] students){ for(Student student:students){ System.out.println("Name:"+student.name+",Id:"+student.id+",Age:"+student.age); } System.out.println("========================================"); } public static void printArray(Integer[] arr){ if(arr==null){ return; } for(int i= 0 ; i<arr.length;i++){ System.out.print(arr[i]+" "); } System.out.println(); }}