2009-09-19 141 views
4

Java中有可能創建PriorityQueue對象,其中決定優先級的鍵是對象的成員?Java中的優先隊列?

我在網上看到的所有例子在PriorityQueue中插入一個整數並檢索它們。我正在尋找一個插入對象實例的實現,並根據它的一個成員值(可能是一個整數)來檢索它。

回答

17

是的,PriorityQueue有一個constructor,允許您通過Comparator來定義元素的順序。例如,如果你有以下Bar類:

public class Bar { 
    private int priority; 

    // getters/setters ... 
} 

你想創建一個優先級隊列它可以根據該priority場的元素(例如,以更大的優先停留項目在隊列的前面) ,你可以使用以下命令:

Queue<Bar> queue = new PriorityQueue<Bar>(new Comparator<Bar>() { 
    public int compare(Bar a1, Bar a2) { 
    return a2.getPriority() - a1.getPriority(); // adapt this to your needs 
    } 
}); 

如果您在compare方法有更復雜的邏輯,或者如果你想重新利用的代碼,那麼我建議你創建一個類,說BarComparator,實現Comparator<Bar>

此外,作爲替代上述,可以使Bar實現Comparable接口,並使用empty構造函數,像這樣:

public class Bar implements Comparable<Bar> { 
    private int priority; 

    @Override 
    public int compareTo(Bar b) { 
    return b.getPriority() - this.priority; 
    } 
} 

希望它能幫助。

+0

當您說按更高的優先級排序時,您的意思是,優先級爲3的Bar具有更高的優先級,然後優先級爲13的Bar,這意味着具有較小優先級值的Bar實際上具有「更高優先級「 – Tomek 2009-09-28 14:59:24

+1

完全相反。優先級爲20的「Bar a」比優先級爲18的「Bar b」具有更高的優先級,因此「Bar a」停留在隊列的前端。 – 2009-09-28 19:54:28