2017-10-21 74 views
1

我正在做一個自定義的優先級隊列,我基本上是物體推到PQ和排序在該對象的特定鍵:瞭解覆蓋在Java優先級隊列中如何與compareTo配合使用?

優先級隊列項類

package Graphs; 

public class PQEntry implements Comparable<PQEntry> { 
    public int node; 
    public int nodeVal; 

    public PQEntry(int node, int nodeVal) { 
     this.node = node; 
     this.nodeVal = nodeVal; 
    } 

    @Override 
    public String toString() { 
     return "Node: " + this.node + ", Value: " + this.nodeVal; 
    } 

    public int getNodeVal() { 
     return this.nodeVal; 
    } 

    @Override 
    public int compareTo(PQEntry other) { 
     return Integer.compare(this.getNodeVal(), other.nodeVal); 
    } 
} 

現在,一切都很好,很正常,優先級的工作,因爲它應該:

PriorityQueue<PQEntry> pq = new PriorityQueue(); 

但我是新來的Java,我很困惑,如何/在哪裏/當我PQEntry類的compareTo被應用到的PriorityQueue類,以及如何,這正是工作。

當我調用PriorityQueue中的add函數時,它是否會啓動一些從我的PQEntry類中調用超級方法的交換算法?我對Java真的有點新鮮,並試圖理解這裏的流程。

回答

0

我會盡力爲你澄清事情。

documentation of PriorityQueue,你會發現它指出:

優先級隊列中的元素進行排序,根據自己的自然順序,或者通過隊列構造的時候提供一個比較,這取決於使用的構造。優先級隊列不允許空元素。依賴於自然順序的優先級隊列也不允許插入非可比對象(這樣做可能導致ClassCastException)。

PriorityQueue期望無論是ComparatorComparable對象。只要提供其中的一個,隊列就會「按原樣工作」,因爲它只依賴於這些接口。

當沒有提供比較器時PriorityQueue會嘗試將元素轉換爲Comparable,然後使用compareTo方法確定如何對它們進行排序。

當提供比較器時,PriorityQueue將簡單地使用該對象執行元素比較並相應地對它們進行排序。

如需進一步閱讀,您可以查看Java Tutorials,特別是lesson on Interfaces and Inheritance