优先队列PriorityQueue是一个堆,默认是小根堆(是一种经过排序的完全二叉树,其中任一非终端节点的数据值均不大于其左子节点和右子节点的值), 即堆顶是最小值,叶子结点大于父节点。
若向PriorityQueue传递一个比较器,可以实现自定义的比较顺序,实现大根堆。
首先看成员变量,核心成员变量是:数组queue, 数组大小size,比较器comparator
transient Object[] queue; // non-private to simplify nested class access
/**
* The number of elements in the priority queue.
*/
private int size = 0;
/**
* The comparator, or null if priority queue uses elements'
* natural ordering.
*/
private final Comparator<? super E> comparator;
核心函数:siftUpComparable ,作用是在每新加一个对象,将该对象放在堆中应该放的位置。
private void siftUpComparable(int k, E x) {
Comparable<? super E> key = (Comparable<? super E>) x;
while (k > 0) {
int parent = (k - 1) >>> 1; // 计算父节点的index
Object e = queue[parent]; // 父节点
if (key.compareTo((E) e) >= 0) // 大于父节点,说明堆不用调整
break;
queue[k] = e; // 小于父节点,父节点已到当前结点,继续调整,直到把key放到应该放的位置
k = parent;
}
queue[k] = key;
}