Java 中的 PriorityQueue 不是确定性的?
PriorityQueue in Java not deterministic?
当我运行以下优先级队列测试时:
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
不能保证确定性行为?
它是不确定的。
来自documentation for PriorityQueue
If multiple elements are tied for least value, the head is one of
those elements -- ties are broken arbitrarily.
当我运行以下优先级队列测试时:
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
不能保证确定性行为?
它是不确定的。
来自documentation for PriorityQueue
If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily.