概述
PriorityQueue 意为优先队列,表示队列中的元素是有优先级的,也就是说元素之间是可比较的。因此,插入队列的元素要实现 Comparable 接口或者 Comparator 接口。
PriorityQueue 的继承结构如下:
通过上图可看出,PriorityQueue 没有实现 BlockingQueue 接口,并非阻塞队列。它在逻辑上使用「堆」(即完全二叉树)结构实现,物理上基于「动态数组」存储。
源码分析
构造器
1、简单构造器
// 构造器 1:无参构造器(默认初试容量为 11)
public PriorityQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
// 构造器 2:指定容量的构造器
public PriorityQueue(int initialCapacity) {
this(initialCapacity, null);
}
// 构造器 3:指定比较器的构造器
public PriorityQueue(Comparator<? super E> comparator) {
this(DEFAULT_INITIAL_CAPACITY, comparator);
}
// 构造器 4:指定初始容量和比较器的构造器
public PriorityQueue(int initialCapacity,
Comparator<? super E> comparator) {
// Note: This restriction of at least one is not actually needed,
// but continues for 1.5 compatibility
if (initialCapacity < 1)
throw new IllegalArgumentException();
// 初始化内部数组和比较器
this.queue = new Object[initialCapacity];
this.comparator = comparator;
}
这几个构造器的作用就是初始化内部数组和比较器。
2、复杂构造器
// 构造器 5:用给定集合初始化 PriorityQueue 对象
public PriorityQueue(Collection<? extends E> c) {
// 如果集合是 SortedSet 类型
if (c instanceof SortedSet<?>) {
SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
this.comparator = (Comparator<? super E>) ss.comparator();
initElementsFromCollection(ss);
}
// 如果集合是 PriorityQueue 类型
else if (c instanceof PriorityQueue<?>) {
PriorityQueue<? extends E> pq = (PriorityQueue<? extends E>) c;
this.comparator = (Comparator<? super E>) pq.comparator();
initFromPriorityQueue(pq);
}
else {
this.comparator = null;
initFromCollection(c);
}
}
initElementsFromCollection:
// 使用给定集合的元素初始化 PriorityQueue
private void initElementsFromCollection(Collection<? extends E> c) {
// 把集合转为数组
Object[] a = c.toArray();
// If c.toArray incorrectly doesn't return Object[], copy it.
if (a.getClass() != Object[].class)
a = Arrays.copyOf(a, a.length, Object[].class);
int len = a.length;
// 确保集合中每个元素不能为空
if (len == 1 || this.comparator != null)
for (int i = 0; i < len; i++)
if (a[i] == null)
throw new NullPointerException();
// 初始化 queue 数组和 size
this.queue = a;
this.size = a.length;
}
initFromPriorityQueue:
private void initFromPriorityQueue(PriorityQueue<? extends E> c) {
if (c.getClass() == PriorityQueue.class) {
// 若给定的是 PriorityQueue,则直接进行初始化
this.queue = c.toArray();
this.size = c.size();
} else {
initFromCollection(c);
}
}
initFromCollection:
private void initFromCollection(Collection<? extends E> c) {
// 将集合中的元素转为数组,并赋值给 queue(上面已分析)
initElementsFromCollection(c);
// 堆化
heapify();
}
heapify: 堆化,即将数组元素转为堆的存储结构
private void heapify() {
// 从数组的中间位置开始遍历即可
for (int i = (size >>> 1) - 1; i >= 0; i--)
siftDown(i, (E) queue[i]);
}
siftDown: 向下筛选?暂未找到恰当的译法,但这不是重点,该方法的作用就是使数组满足堆结构(其思想与冒泡排序有些类似)。如下:
private void siftDown(int k, E x) {
// 根据 comparator 是否为空采用不同的方法
if (comparator != null)
siftDownUsingComparator(k, x);
else
siftDownComparable(k, x);
}
siftDownUsingComparator:
private void siftDownUsingComparator(int k, E x) {
// 数组的中间位置
int half = size >>> 1;
while (k < half) {
// 获取索引为 k 的节点的左子节点索引
int child = (k << 1) + 1;
// 获取 child 的值
Object c = queue[child];
// 获取索引为 k 的节点的右子节点索引
int right = child + 1;
// 左子节点的值大于右子节点,则二者换位置
if (right < size &&
comparator.compare((E) c, (E) queue[right]) > 0)
// 取左右子节点中较小的一个
c = queue[child = right];
// 给定的元素 x 与较小的子节点的值比较
if (comparator.compare(x, (E) c) <= 0)
break;
// 将该节点与子节点互换
queue[k] = c;
k = child;
}
queue[k] = x;
}
siftDownComparable 方法代码如下:
private void siftDownComparable(int k, E x) {
Comparable<? super E> key = (Comparable<? super E>)x;
int half = size >>> 1; // loop while a non-leaf
while (k < half) {
int child = (k << 1) + 1; // assume left child is least
Object c = queue[child];
int right = child + 1;
if (right < size &&
((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
c = queue[child = right];
if (key.compareTo((E) c) <= 0)
break;
queue[k] = c;
k = child;
}
queue[k] = key;
}
此方法与 siftDownUsingComparator 方法实现逻辑完全一样,不同的的地方仅在于该方法是针对 Comparable 接口,而后者针对 Comparator 接口,不再赘述。
此外 PriorityQueue 还有两个构造器,但都是通过上面的方法实现的,如下:
// 构造器 6:用给定的 PriorityQueue 初始化一个 PriorityQueue
public PriorityQueue(PriorityQueue<? extends E> c) {
this.comparator = (Comparator<? super E>) c.comparator();
initFromPriorityQueue(c);
}
// 构造器 7:用给定的 SortedSet 初始化 PriorityQueue
public PriorityQueue(SortedSet<? extends E> c) {
this.comparator = (Comparator<? super E>) c.comparator();
initElementsFromCollection(c);
}
成员变量
// 数组的默认初始容量
private static final int DEFAULT_INITIAL_CAPACITY = 11;
// 内部数组,用于存储队列中的元素
transient Object[] queue; // non-private to simplify nested class access
// 队列中元素的个数
private int size = 0;
// 队列中元素的比较器
private final Comparator<? super E> comparator;
// 结构性修改次数
transient int modCount = 0; // non-private to simplify nested class access
常用方法
add(E), offer(E) 两个入队操作方法如下:
// 实际是调用 offer 方法实现的
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 static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// 原先容量
int oldCapacity = queue.length;
// Double size if small; else grow by 50%
// 原容量较小时,扩大为原先的两倍;否则扩大为原先的 1.5 倍
int newCapacity = oldCapacity + ((oldCapacity < 64) ?
(oldCapacity + 2) :
(oldCapacity >> 1));
// overflow-conscious code
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 创建一个新的数组
queue = Arrays.copyOf(queue, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
出队操作:
public E poll() {
// 队列为空时,返回 null
if (size == 0)
return null;
int s = --size;
modCount++;
// 队列第一个元素
E result = (E) queue[0];
// 队列最后一个元素
E x = (E) queue[s];
// 把最后一个元素置空
queue[s] = null;
if (s != 0)
// 下沉
siftDown(0, x);
return result;
}
总结
(1)PriorityQueue是一个小顶堆;
(2)PriorityQueue是非线程安全的;
(3)PriorityQueue不是有序的,只有堆顶存储着最小的元素;
(4)入队就是堆的插入元素的实现;
(5)出队就是堆的删除元素的实现;