优先级队列
程序员文章站
2022-06-10 14:22:25
...
注:用了一把系统的优先级队列,但是必须自定义比较器
package lesson01;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Code01_PriorityQueue {
public static void main(String[] args) {
PriorityQueue<Student> min_heap = new PriorityQueue<>(new IdAscendingComparator() );
Student s1 = new Student("x", 1001);
Student s2 = new Student("y", 1002);
Student s3 = new Student("z", 1003);
min_heap.add(s3);
min_heap.add(s1);
min_heap.add(s2);
while(! min_heap.isEmpty()) {
Student student = min_heap.poll();
System.out.println("Student [name=" + student.name + ", id=" + student.id + "]");
}
}
}
class IdAscendingComparator implements Comparator<Student>{
// 自定义升序
public int compare(Student o1, Student o2) {
return o1.id - o2.id;
}
}
class Student{
String name;
int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
}
上一篇: 【面试】常见的前端面试题(1)
下一篇: 这条sql如何查询