我打算使用的PriorityQueue作爲最小堆了5個元素,每個元素都被聲明爲以下一個元組:爲什麼我的Java的PriorityQueue的行爲奇怪
public class Tuple implements Comparator<Tuple> {
public final int x;
public final double y;
public Tuple(int x, double y) {
this.x = x;
this.y = y;
}
public Tuple() {
this.x = 0;
this.y = 0;
}
@Override
public int compare(Tuple o1, Tuple o2) {
return (int) (o1.y - o2.y);
}
}
然後,我宣佈我堆中
PriorityQueue<Tuple> heap = new PriorityQueue<Tuple>(5, new Tuple());
int capacity = 5;
然後,我用下面的代碼添加元素:
其中if (capacity != 0) {
if (score > 0) {
Tuple tmp = new Tuple(i, score);
heap.add(tmp);
capacity -= 1;
}
} else {
if (score > heap.peek().y) {
OutPutPriorityQueue(heap);
Tuple tmp = new Tuple(i, score);
heap.remove();
heap.add(tmp);
OutPutPriorityQueue(heap);
}
}
,score
是double
別處計算OutPutPriorityQueue
聲明如下:
public void OutPutPriorityQueue(PriorityQueue<Tuple> heap){
Tuple [] temp = new Tuple[5];
for (int i=0;i<5;i++){
temp[i] = heap.poll();
System.out.print(temp[i].y+"\t");
}
System.out.println();
for (int i=0; i<5; i++){
heap.add(temp[i]);
}
}
對不起,我列出了太多的代碼在這裏,但是這是我第一次使用PriorityQueue的,我不知道哪裏出了問題和代碼的邏輯應該很簡單。
然後我的問題是,我的功能OutPutPriorityQueue
,這是應該根據爲了打印元件,打印在基本上任意方式的元件的輸出,這裏是一些示例:
0.5549890273805606 0.6479515952918626 0.8593378488473195 0.53232731034541 1.0
1.0 0.8593378488473195 0.53232731034541 0.8593378488473195 0.6479515952918626
1.0 0.6479515952918626 0.8593378488473195 0.53232731034541 0.8593378488473195
0.8593378488473195 1.6093378488473196 0.53232731034541 0.8593378488473195 0.6479515952918626
0.8593378488473195 0.6479515952918626 0.8593378488473195 0.53232731034541 1.6093378488473196
1.6093378488473196 1.28601715282334 0.53232731034541 0.8593378488473195 0.6479515952918626
這些數字很難看,但它的行爲可以概括爲以下幾點:
- 每
remove()
和add()
去除頭一個,將第5一個頭,並插入在第二位的一個新的。 - 行
2n-1
應該與行2n
完全一樣,但它們是不同的。注:第二個(最新的)被換與第五一個 - 似乎沒有在此隊列中定義的順序,但我定義了一個
compare()
,並通過它英寸
我不知道爲什麼這個正在發生,我希望有人能幫助我。
我正確使用compare()
嗎?或者是其他東西?
非常感謝!
閱讀[二元堆](http://en.wikipedia.org/wiki/Binary_heap),這就是'PriorityQueue'的實現方式。 –
謝謝@SotiriosDelimanolis,但這隻會讓我的堆表現得更加奇怪,不是嗎? –
你能發佈一個完整的工作示例,以便我可以準確地再現你需要解釋的內容嗎? –