优先队列实现

问题描述:

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

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被定义为返回的最小元素,而不是最大的元素,你可以通过检查文档找到。

该队列的头部是相对于 指定排序的最小元素。如果多个元素的值最小,那么头部就是其中一个元素 - 任意断开连接。队列检索操作轮询,删除,查看和元素访问队列头部的 元素。

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

+0

非常感谢您的帮助 – user2326847 2013-05-11 12:31:08