优先级队列
原创
©著作权归作者所有:来自51CTO博客作者塞上江南o的原创作品,请联系作者获取转载授权,否则将追究法律责任
注:用了一把系统的优先级队列,但是必须自定义比较器
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;
}
}