/** * 构造一个具有指定初始容量的优先队列。 * * @param initialCapacity 优先队列的初始容量 * @throws IllegalArgumentException 如果指定的初始容量为负 */ publicPriorityQueue(int initialCapacity) { // Note: This restriction of at least one is not actually needed, // but continues for 1.5 compatibility if (initialCapacity < 1) thrownewIllegalArgumentException(); this.elements = newObject[initialCapacity]; }
/** * 添加元素 * * @param e 要添加的元素 * @return 如果队列由于调整大小而更改,则为 true * @throws NullPointerException 如果指定的元素为 null */ @Override publicbooleanoffer(E e) { if (e == null) thrownewNullPointerException(); inti= size; if (i >= elements.length) grow(i + 1); siftUp(i, e); size = i + 1; returntrue; }
/** * 上浮操作 * 在位置 k 处插入项 x,通过将 x 沿树向上提升直到它大于或等于其父项,或者是根,来保持堆不变性。 * 与 siftDown 类似 */ privatevoidsiftUp(int k, E x) { siftUpComparable(k, x, elements); }
/** * Increases the capacity of the array. * * @param minCapacity the desired minimum capacity */ privatevoidgrow(int minCapacity) { intoldCapacity= elements.length; // Double size if small; else grow by 50% intnewCapacity= newLength(oldCapacity, minCapacity - oldCapacity, /* minimum growth */ oldCapacity < 64 ? oldCapacity + 2 : oldCapacity >> 1 /* preferred growth */); elements = Arrays.copyOf(elements, newCapacity); }
/** * Inserts the specified element into this priority queue. * * @return {@code true} (as specified by {@link Queue#offer}) * @throws ClassCastException if the specified element cannot be * compared with elements currently in this priority queue * according to the priority queue's ordering * @throws NullPointerException if the specified element is null */ @Override public E poll() { final Object[] es; final E result;
/** * Retrieves, but does not remove, the head of this queue. * * @return the head of this queue, or {@code null} if this queue is empty */ @Override public E peek() { return (E) elements[0]; } }