数组容纳元素
transient Object[] queue
队列中元素的数量
int size;
构造函数,容量默认为11
public PriorityQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
添加元素
public boolean add(E e) {
return offer(e);
}
元素为null,抛出异常
public boolean offer(E e) {
if (e == null)
throw new NullPointerException();
modCount++;
获取当前元素数量
int i = size;
队列满了,扩容
if (i >= queue.length)
grow(i + 1);
将元素放入队列中合适的位置,符合堆结构
siftUp(i, e);
size = i + 1;
return true;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
扩容方法
private void grow(int minCapacity) {
int oldCapacity = queue.length;
// 小于等于64,则扩容2倍+2,大于64 扩容1.5倍
int newCapacity = oldCapacity + ((oldCapacity < 64) ?
(oldCapacity + 2) :
(oldCapacity >> 1));
// 如果扩容后超出限制,进行hugeCapacity
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;
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
private void siftUp(int k, E x) {
if (comparator != null)
siftUpUsingComparator(k, x, queue, comparator);
else
siftUpComparable(k, x, queue);
}
private static <T> void siftUpUsingComparator(int k, T x, Object[] es, Comparator<? super T> cmp) {
while (k > 0) {
找到当前插入元素的父元素
int parent = (k - 1) >>> 1;
Object e = es[parent];
如果比较结果<0,则继续向上比较,
if (cmp.compare(x, (T) e) >= 0)
break;
es[k] = e;
k = parent;
}
es[k] = x;
}
取出元素,(取出队首元素)
public E poll() {
final Object[] es;
final E result;
if ((result = (E) ((es = queue)[0])) != null) {
modCount++;
final int n;
取出队尾元素,
final E x = (E) es[(n = --size)];
es[n] = null;
if (n > 0) {
将队尾元素从头开始向下比较,放入合适的位置
final Comparator<? super E> cmp;
if ((cmp = comparator) == null)
siftDownComparable(0, x, es, n);
else
siftDownUsingComparator(0, x, es, n, cmp);
}
}
return result;
}