PriorityQueue实现一个优先队列
从队首获取元素时,总是获取到优先级最高的元素
默认元素比较顺序排序,必须实现comparator接口
可以通过Comparator自定义排序,这样不必实现comparator接口
//实现Comaparable接口
public class Person implements Comparable<Person>{
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Person o) {
return this.name.compareTo(o.name);
}
}
public class Student {
private String name;
private Integer score;
public Student(String name, Integer score) {
this.name = name;
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", score=" + score +
'}';
}
public String getName() {
return name;
}
public Integer getScore() {
return score;
}
}
public class Main {
public static void main(String[] args) {
Queue<Person> queue=new PriorityQueue<>();
queue.add(new Person("xiaozhang",10));
queue.add(new Person("zhangsan",10));
queue.add(new Person("lisi",10));
System.out.println(queue.remove());
Queue<Student> queue1=new PriorityQueue<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//按照score的倒序输出
return -o1.getScore().compareTo(o2.getScore());
}
});
queue1.add(new Student("xiaozhang",100));
queue1.add(new Student("zhangsan",80));
queue1.add(new Student("lisi",70));
System.out.println(queue1.poll());
}