问题
When I run the following priority queue test:
class Run {
public static void main(String[] args) {
PriorityQueue<Entry> q = new PriorityQueue<>(8, Collections.reverseOrder(new Comparator<Entry>() {
@Override
public int compare(Entry o1, Entry o2) {
return Integer.compare(o1.getValue(), o2.getValue());
}
}));
q.offer(new Entry(100));
q.offer(new Entry(0));
q.offer(new Entry(1));
q.offer(new Entry(-1));
q.offer(new Entry(0));
q.offer(new Entry(1));
q.offer(new Entry(-100));
q.offer(new Entry(100));
while (q.peek() != null) {
System.out.println(q.poll());
}
}
private static class Entry {
private static int GLOBAL_ID = 0;
private final int value, id;
public Entry(int value) {
this.value = value;
id = GLOBAL_ID++;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return "Entry[" + id + ", value = " + value + ']';
}
}
}
I get the following result:
Entry[0, value = 100]
Entry[7, value = 100]
Entry[2, value = 1]
Entry[5, value = 1]
Entry[4, value = 0]
Entry[1, value = 0]
Entry[3, value = -1]
Entry[6, value = -100]
I expect equal elements to be output in the same order as they are being input, so when entry 0 is offered before entry 7, it is also polled before 7 is polled. But why is entry 4 suddenly polled before the 1? Is it the erroneous Comparator
or does PriorityQueue
not guarantee a deterministic behaviour?
回答1:
It is non-deterministic.
From the documentation for PriorityQueue
If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily.
来源:https://stackoverflow.com/questions/27865331/priorityqueue-in-java-not-deterministic