2013-05-11 124 views
0

我試圖建立一個優先級隊列,但是當我測試它時似乎有一些不一致。我忽略了方法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()); 
} 

回答

2

Java的java.util.PriorityQueue被定義爲返回的最小元素,而不是最大的元素,你可以通過檢查文檔找到。

該隊列的頭部是相對於 指定排序的最小元素。如果多個元素的值最小,那麼頭部就是其中一個元素 - 任意斷開連接。隊列檢索操作輪詢,刪除,查看和元素訪問隊列頭部的 元素。

優先級隊列是基於最小值還是最大值取決於語言和庫,但最小隊列是我看到的最常見的隊列。

+0

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