如果你看看源代碼,每次你poll()
在PriorityQueue
它resifts時間,但它總是返回該項目是爲在篩前頂部。
public class PQ {
int priority;
public PQ(int priority) {
this.priority = priority;
}
public static void main(String[] args) {
PQ one = new PQ(1);
PQ two = new PQ(2);
PQ three = new PQ(3);
PQ four = new PQ(4);
PQ five = new PQ(5);
PriorityQueue<PQ> q = new PriorityQueue<PQ>(3, new Comparator<PQ>() {
@Override
public int compare(PQ o1, PQ o2) {
return o1.priority-o2.priority;
}
});
q.add(three);
q.add(one);
q.add(four);
q.add(two);
q.add(five);
//Prints;
//PQ-1
//PQ-2
//PQ-3
//PQ-4
//PQ-5
while (!q.isEmpty()) {
System.out.println(q.poll());
}
q.add(three);
q.add(one);
q.add(four);
q.add(two);
q.add(five);
//Change the priority after it has been queued
four.priority = 10;
//Prints;
//PQ-1
//PQ-2
//PQ-3
//PQ-5
//PQ-10
while (!q.isEmpty()) {
System.out.println(q.poll());
}
//Reset the priority
four.priority = 4;
q.add(three);
q.add(one);
q.add(four);
q.add(two);
q.add(five);
//Change the priority after it has been queued
four.priority = 0;
//Prints;
//PQ-1
//PQ-0
//PQ-2
//PQ-3
//PQ-5
while (!q.isEmpty()) {
System.out.println(q.poll());
}
}
public String toString() {
return "PQ-" + priority;
}
}
有趣。不如我希望的那麼好,但比我擔心的要好! –