我只想知道Comparator使用哪種排序技術來排序事物。並且即使我們從不明確調用此方法,也會調用它的方法compare()
。 例如可以說我有類比較器在內部使用哪種比較值以及它如何調用其比較方法?
class Person{
int age;
int personId;
//..getters and setters goes here
}
我有另一個類SortPerson
class SortPerson implements Comparator<Person>{
public int compare(){
//sorting logic goes here
//Assume that I am sorting according to person age.
}
}
在我的主類我使用的PriorityQueue
class Main{
public void main(...){
Queue<Person> q = new PriorityQueue<Person>(5, new SortPerson());
//q.add() and q.poll() operations goes here
}
}
的比較是那麼究竟怎麼了在執行添加和輪詢操作時調用以維護正確的排序順序? 謝謝。
源代碼將更好地回答這個問題。 –
「比較器」不使用任何排序技術。它是執行排序的'PriorityQueue'(等)。 –
@Oli Charlesworth:是嗎?但是如果我想按相反順序排序,那麼我通常只在'compare()'方法中寫這個邏輯。那麼,如果PriorityQueue完成所有排序,我們爲什麼要使用Comparator呢?請詳細說明,這確實會有幫助。 – Winn