当我运行以下优先级队列测试时:
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 + ']';
}
}
}
我得到以下结果:
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]
我希望相同的元素以与它们输入相同的顺序输出,因此当在条目7之前提供条目0时,也会在轮询7之前轮询它。但为什么入口4突然在1之前被调查?是错误的Comparator
还是PriorityQueue
不保证确定性行为?