PriorityQueue 基于小根堆,如果需要大根堆,就在构造函数里面自定义 Comparator。因为 PriorityQueue 必须支持比较运算,所以不能为 null。PriorityQueue 不是线程安全的,如果需要在多线程下使用,应该使用 PriorityBlockingQueue。
看一下 PriorityQueue 的 add 方法:
public boolean add(E e) {
return offer(e);
}
public boolean offer(E e) {
if (e == null)
throw new NullPointerException();
modCount++;
int i = size;
if (i >= queue.length)
grow(i + 1);
size = i + 1;
if (i == 0)
queue[0] = e;
else
siftUp(i, e);
return true;
}
private void grow(int minCapacity) {
int oldCapacity = queue.length;
// Double size i