java无法理解PriorityQueue如何更改排序顺序?
import java.util.*;
class abc {
public static void main(String args[]){
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
pq.add(1);
pq.add(2);
pq.add(3);
pq.add(4);
pq.add(5);
pq.add(6);
System.out.println(pq);
pq.remove();
System.out.println(pq);
}
}
当我移除元素时,顺序会改变。 根据字典排序,输出应按升序排列。但我得到的结果是:
# 1 楼答案
PriorityQueue
实现一个堆数据结构。此数据结构具有使元素保持部分排序的属性。Heap是一个二叉树(即使实际上它是在数组中实现的),它保持以下不变性:如果节点P有一个子C,则P的值小于/大于C的值因此,只有第一个元素(根)保证是集合的最小值/最大值,而所有其他值仅部分排序
为什么这么做?如果必须保留完整的排序集合,则插入/删除操作将采用
O(n)
,而对于堆数据结构,它们都是O(log n)
。如果您只对集合的max/min感兴趣,那么PriorityQueue
比完整的排序数组有显著的优势# 2 楼答案
从^{} 的
toString()
方法的文档中(将队列传递给System.out.println()
方法时会调用该方法):从^{} 的
iterator()
方法的文档中:这就是你的答案
# 3 楼答案
调用
System.out.println(pq);
与调用System.out.println(pq.toString());
相同如果你看一下documentation of the the toString() method,你会发现它说:
我强调了重要的部分。所以我们需要看一下documentation of the iterator of the priority queue,它表明:
因此,代码的输出不允许对优先级队列施加的顺序得出任何结论
在main documentation of the PriorityQueue中写道: