关于java:优先队列实现

Priority queue implementation

我试图建立一个优先队列,但我测试它时似乎有些不一致。我覆盖了方法 compareTo() 但不知何故它返回了年龄最小的学生。这是为什么 ?不应该是22岁(最高)的学生吗?这是代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Student implements Comparable<Student> {

   private String name;
   private int age;

   public Student(int i) {
      age = i;
   }
   public int getAge(){
    return this.age;
   }

   public int print(){
    return age;
   }
   @Override
   public int compareTo(Student s) {
    if(this.age < s.getAge()){return -1;}
    else if(this.age > s.getAge()){return 1;}
    else{return 0;}
   }
    public static void main(String[] args) {
        Queue<Student> q = new PriorityQueue<Student>();
        q.offer(new Student(21));
        q.offer(new Student(18));
        q.offer(new Student(22));

        Student s = q.poll();
        System.out.println(s.print());
}

Java 的 java.util.PriorityQueue 被定义为返回最小元素,而不是最大元素,您可以通过查看文档找到。

The head of this queue is the least element with respect to the
specified ordering. If multiple elements are tied for least value, the
head is one of those elements -- ties are broken arbitrarily. The
queue retrieval operations poll, remove, peek, and element access the
element at the head of the queue.

优先级队列是基于最小值还是最大值取决于语言和库,但最小队列是我见过的最常见的。