// 指定元素比较器的构造方法 publicPriorityQueue(Comparator<? super E> comparator){ this(DEFAULT_INITIAL_CAPACITY, comparator); }
// 指定元素比较器和数组长度的构造方法 publicPriorityQueue(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) thrownew IllegalArgumentException(); this.queue = new Object[initialCapacity]; this.comparator = comparator; }
// 新增元素 publicbooleanoffer(E e){ if (e == null) thrownew 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);// 对新增元素做上浮操作 returntrue; }
// 弹出队首元素 public E poll(){ if (size == 0) returnnull; 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 E removeAt(int i){ // assert i >= 0 && i < size; modCount++; int s = --size; if (s == i) // removed last element queue[i] = null; else { E moved = (E) queue[s]; queue[s] = null; siftDown(i, moved);// 对队尾元素做下沉操作 if (queue[i] == moved) {// 判断moved元素没有改变 siftUp(i, moved);// 进行一次上浮操作 if (queue[i] != moved) return moved; } } returnnull; }