我正在做一個自定義的優先級隊列,我基本上是物體推到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真的有點新鮮,並試圖理解這裏的流程。