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; }
// 这一步就是PriorityQueue的关键部分 privatevoidsiftUp(int k, E x){ // 若comparator不为空,则使用用户给定的comparator,否则则使用元素本身提供的比较器 if (comparator != null) siftUpUsingComparator(k, x); else siftUpComparable(k, x); }
@SuppressWarnings("unchecked") // comparator为空时调用 privatevoidsiftUpComparable(int k, E x){ // 获取元素本身,并转化为可Comparable类型 Comparable<? super E> key = (Comparable<? super E>) x; // 若k>0,即k未处于根元素位置 while (k > 0) { int parent = (k - 1) >>> 1; Object e = queue[parent]; if (key.compareTo((E) e) >= 0) break; queue[k] = e; k = parent; } queue[k] = key; }
@SuppressWarnings("unchecked") // comparator不为空时调用 privatevoidsiftUpUsingComparator(int k, E x){ while (k > 0) { int parent = (k - 1) >>> 1; Object e = queue[parent]; // 使用用户给定的comparator if (comparator.compare(x, (E) e) >= 0) break; queue[k] = e; k = parent; } queue[k] = x; }
删除操作 - poll()
1 2 3 4 5 6 7 8 9 10 11 12
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; }
privatevoidsiftDown(int k, E x){ if (comparator != null) siftDownUsingComparator(k, x); else siftDownComparable(k, x); }
@SuppressWarnings("unchecked") privatevoidsiftDownComparable(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; }
@SuppressWarnings("unchecked") privatevoidsiftDownUsingComparator(int k, E x){ int half = size >>> 1; while (k < half) { int child = (k << 1) + 1; Object c = queue[child]; int right = child + 1; if (right < size && comparator.compare((E) c, (E) queue[right]) > 0) c = queue[child = right]; if (comparator.compare(x, (E) c) <= 0) break; queue[k] = c; k = child; } queue[k] = x; }
查找操作 - peek()
1 2 3 4
// 时间复杂度O(1) public E peek(){ return (size == 0) ? null : (E) queue[0]; }