比较器
- 比较器的实质就是重载比较运算符
- 比较器可以很好地应用在特殊标准的排序上
- 比较器可以很好地应用在特殊标准排序的结构上
- 写代码变得异常容易,还用于范型编程
语言提供的堆结构 VS 手写的堆结构
- 取决于,你有没有动态该信息的需求!
- 语言提供的堆结构,如果你动态改数据,不保证依然有序
- 手写堆结构,因为增加了对象的位置表,所以能够满足动态改信息的需求
package com.harrison.class04;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Code04_Comparator {
public static class MyComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}
public static void main(String[] args) {
PriorityQueue<Integer> heap = new PriorityQueue<>(new MyComparator());
heap.add(4);
heap.add(9);
heap.add(-3);
heap.add(3);
heap.add(99);
while (!heap.isEmpty()) {
System.out.println(heap.poll());
}
}
}
package com.harrison.class04;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TreeMap;
public class Code05_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 IdAscendingAgeDescendOrder implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return (o1.id==o2.id)?(o2.age-o1.age):o1.id-o2.id;
}
}
public static class IdAscendingComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o1.id-o2.id;
}
}
public static class IdDescendComparator implements Comparator<Student>{
@Override
public int compare(Student o1, Student o2) {
return o2.id-o1.id;
}
}
public static void printStudents(Student[] students) {
for(Student student:students) {
System.out.println("Name:"+student.name+",Id:"+student.id+",Age:"+student.age);
}
}
public static void main(String[] args) {
Student s1=new Student("A", 5, 34);
Student s2=new Student("B", 2, 23);
Student s3=new Student("C", 9, 32);
Student s4=new Student("D", 2, 18);
Student s5=new Student("E", 8, 21);
Student[] students=new Student[] {s1,s2,s3,s4,s5};
System.out.println("第一条打印:");
Arrays.sort(students,new IdAscendingAgeDescendOrder());
for(int i=0; i<students.length; i++) {
Student s=students[i];
System.out.println(s.id+","+s.name+","+s.age);
}
System.out.println("第二条打印");
ArrayList<Student> stuList=new ArrayList<>();
stuList.add(s1);
stuList.add(s2);
stuList.add(s3);
stuList.add(s4);
stuList.add(s5);
stuList.sort(new IdAscendingAgeDescendOrder());
for(int i=0; i<stuList.size(); i++) {
Student s=stuList.get(i);
System.out.println(s.id+","+s.name+","+s.age);
}
System.out.println("第三条打印");
s1=new Student("A", 4, 40);
s2=new Student("B", 4, 21);
s3=new Student("C", 4, 12);
s4=new Student("D", 4, 62);
s5=new Student("E", 4, 42);
TreeMap<Student, String> treeMap=new TreeMap<>((a,b)->(a.id-b.id));
treeMap.put(s1, "我是学生1,我的名字叫A");
treeMap.put(s2, "我是学生2,我的名字叫B");
treeMap.put(s3, "我是学生3,我的名字叫C");
treeMap.put(s4, "我是学生4,我的名字叫D");
treeMap.put(s5, "我是学生5,我的名字叫E");
for(Student s:treeMap.keySet()) {
System.out.println(s.id+","+s.name+","+s.age);
}
}
}