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;
}
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)
//第一次添加元素,直接放到第0个位置即可
queue[0] = e;
else
//需要将元素放到最后,再做上滤操作
siftUp(i, e);
return true;
}
private void grow(int minCapacity) {
int oldCapacity = queue.length;
// Double size if small; else grow by 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);
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 siftUpUsingComparator(int k, E x) {
while (k > 0) {
//计算父亲节点的下标
int parent = (k - 1) >>> 1;
Object e = queue[parent];
//与父节点进行比较
if (comparator.compare(x, (E) e) >= 0)
break;
queue[k] = e;
k = parent;
}
queue[k] = x;
}
public E poll() {
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;
}
private void siftDownUsingComparator(int k, E x) {
int half = size >>> 1;
//这里k必须有孩子,故叶节点需要比较
while (k < half) {
//以下几行代码到较小的那个儿子,用变量c表示
int child = (k << 1) + 1;
//这里假设左儿子比较小
Object c = queue[child];
int right = child + 1;
//左右儿子比较,如果右儿子小则将c赋值为右儿子
if (right < size &&
comparator.compare((E) c, (E) queue[right]) > 0)
c = queue[child = right];
//如果x比小儿子还小,说明k就是正确位置
if (comparator.compare(x, (E) c) <= 0)
break;
queue[k] = c;
k = child;
}
queue[k] = x;
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有