PriorityQueue是基于堆的无界优先队列实现。堆的子节点都不大于(最小堆)或都不小于(最大堆)的一种近似完全二叉树的数据结构。
堆用数组实现,用数组的index作为索引。且 i 的父节点为 [i/2],子节点为[2i], [2i + 1],从数组的index=1开始计算(ProrityQueue中是从index=0开始存储的)。
PriorityQueue 基本结构
public class PriorityQueue<E> extends AbstractQueue<E>
implements java.io.Serializable {
...
//基于数组的实现
transient Object[] queue;
//队列中实际大小
private int size = 0;
//比较器,可以指定,没有指定使用自然顺序
private final Comparatorsuper E> comparator;
...
}
add() && offer()
//add本质是offer()的实现
public boolean add(E e) {
return offer(e);
}
public boolean offer(E e) {
//不可添加null元素
if (e == null)
throw new NullPointerException();
modCount++;
int i = size;
// size > capcatiry时需要扩容
if (i >= queue.length)
grow(i + 1);
size = i + 1;
if (i == 0)
queue[0] = e;
else
//基于堆的实现,添加元素上浮调整堆结构
siftUp(i, e);
return true;
}
private void siftUp(int k, E x) {
//如果comparator不为null,使用指定的比较器的顺序。如果comparator为null,使用自然顺序。本质上只有比较的方法不一样,上浮操作还是一样的
if (comparator != null)
siftUpUsingComparator(k, x);
else
siftUpComparable(k, x);
}
@SuppressWarnings("unchecked")
private void siftUpComparable(int k, E x) {
Comparablesuper E> key = (Comparablesuper E>) x;
while (k > 0) {
int parent = (k - 1) >>> 1;
Object e = queue[parent];
// 当parent元素比添加的元素大,元素下沉
if (key.compareTo((E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
//将元素放在合适的位置
queue[k] = key;
}
在无界的过程中,add() & offer() 不会抛出异常
堆构建过程图示:
堆构建过程中,需要添加的位置,与parent比较,如果parent的优先级较低,那么往下移动,待插入元素上浮(上浮名称的由来)。直到找到合适的位置。
数据构建过程图示:
可以看到,添加过程中的操作是上浮的过程。时间复杂度与其构建的堆深度有关,故其时间复杂度为O(logN)
grow() 扩容
private void grow(int minCapacity) {
int oldCapacity = queue.length;
// 数据比较小就扩大到2倍,否则增大50%
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);
}
remove() && poll()
@SuppressWarnings("unchecked")
public E poll() {
if (size == 0)
return null;
int s = --size;
modCount++;
//删除并返回的是index=0的位置
E result = (E) queue[0];
//删除完之后重建堆,下沉
E x = (E) queue[s];
queue[s] = null;
if (s != 0)
siftDown(0, x);
return result;
}
// 根据是否有comparator来排序
private void siftDown(int k, E x) {
if (comparator != null)
siftDownUsingComparator(k, x);
else
siftDownComparable(k, x);
}
private void siftDownComparable(int k, E x) {
Comparablesuper E> key = (Comparablesuper E>)x;
int half = size >>> 1; // loop while a non-leaf
while (k < half) {
// 将较大的孩子往上移,直到找到合适的位置k
int child = (k << 1) + 1; // assume left child is least
Object c = queue[child];
int right = child + 1;
if (right < size &&
((Comparablesuper 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;
}
删除重建堆过程:
最后一个元素放在index=0。较小的元素上浮到parent, 直到到叶子节点或者合适的位置.
element() && peek()
public E peek() {
//就是这么简单粗暴啊~
return (size == 0) ? null : (E) queue[0];
}
remove(Object obj)
remove(Object obj)需要先找到obj所在的位置。然后removeAt()。删除的过程与remove()类似。查询对应的index的过程:
private int indexOf(Object o) {
if (o != null) {
// 循环数组
for (int i = 0; i < size; i++)
if (o.equals(queue[i]))
return i;
}
return -1;
}
PriorityQueue总结
PriorityQueue的顺序可以根据指定的Comparator或者自然顺序实现,元素需要实现Comparator,否者会有Cast Exception。
PriorityQueue中添加的元素不可为null。
PriorityQueue中的方法没有实现同步。
offer && poll && remove && add 时间复杂度O(logN)
remove(Object obj) && contains(Object obj) 时间复杂度为O(N)
peek && element && size 时间复杂度O(1)