publicPriorityBlockingQueue(int initialCapacity, Comparator<? super E> comparator) { if (initialCapacity < 1) thrownewIllegalArgumentException(); this.comparator = comparator; this.queue = newObject[Math.max(1, initialCapacity)]; }
publicPriorityBlockingQueue(Collection<? extends E> c) { booleanheapify=true; // true if not known to be in heap order booleanscreen=true; // true if must screen for nulls if (c instanceof SortedSet<?>) { SortedSet<? extendsE> ss = (SortedSet<? extendsE>) c; this.comparator = (Comparator<? super E>) ss.comparator(); heapify = false; } elseif (c instanceof PriorityBlockingQueue<?>) { PriorityBlockingQueue<? extendsE> pq = (PriorityBlockingQueue<? extendsE>) c; this.comparator = (Comparator<? super E>) pq.comparator(); screen = false; if (pq.getClass() == PriorityBlockingQueue.class) // exact match heapify = false; } Object[] es = c.toArray(); intn= es.length; // If c.toArray incorrectly doesn't return Object[], copy it. if (es.getClass() != Object[].class) es = Arrays.copyOf(es, n, Object[].class); if (screen && (n == 1 || this.comparator != null)) { for (Object e : es) if (e == null) thrownewNullPointerException(); } this.queue = ensureNonEmpty(es); this.size = n; if (heapify) heapify(); }
privatestatic <T> voidsiftDownComparable(int k, T x, Object[] es, int n) { // assert n > 0; Comparable<? super T> key = (Comparable<? super T>)x; inthalf= n >>> 1; // loop while a non-leaf while (k < half) { // 堆顶元素的孩子节点 intchild= (k << 1) + 1; // assume left child is least Objectc= es[child]; intright= child + 1; if (right < n && ((Comparable<? super T>) c).compareTo((T) es[right]) > 0) c = es[child = right]; if (key.compareTo((T) c) <= 0) break; es[k] = c; k = child; } es[k] = key; }