ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/PriorityQueue.java
(Generate patch)

Comparing jsr166/src/main/java/util/PriorityQueue.java (file contents):
Revision 1.84 by jsr166, Sat Jan 19 18:11:56 2013 UTC vs.
Revision 1.123 by jsr166, Sun May 6 16:26:03 2018 UTC

# Line 1 | Line 1
1   /*
2 < * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
2 > * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
3   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4   *
5   * This code is free software; you can redistribute it and/or modify it
# Line 24 | Line 24
24   */
25  
26   package java.util;
27 < import java.util.stream.Stream;
28 < import java.util.Spliterator;
29 < import java.util.stream.Streams;
30 < import java.util.function.Block;
27 >
28 > import java.util.function.Consumer;
29 > import jdk.internal.misc.SharedSecrets;
30  
31   /**
32   * An unbounded priority {@linkplain Queue queue} based on a priority heap.
# Line 56 | Line 55 | import java.util.function.Block;
55   * <p>This class and its iterator implement all of the
56   * <em>optional</em> methods of the {@link Collection} and {@link
57   * Iterator} interfaces.  The Iterator provided in method {@link
58 < * #iterator()} is <em>not</em> guaranteed to traverse the elements of
58 > * #iterator()} and the Spliterator provided in method {@link #spliterator()}
59 > * are <em>not</em> guaranteed to traverse the elements of
60   * the priority queue in any particular order. If you need ordered
61   * traversal, consider using {@code Arrays.sort(pq.toArray())}.
62   *
# Line 67 | Line 67 | import java.util.function.Block;
67   * java.util.concurrent.PriorityBlockingQueue} class.
68   *
69   * <p>Implementation note: this implementation provides
70 < * O(log(n)) time for the enqueing and dequeing methods
70 > * O(log(n)) time for the enqueuing and dequeuing methods
71   * ({@code offer}, {@code poll}, {@code remove()} and {@code add});
72   * linear time for the {@code remove(Object)} and {@code contains(Object)}
73   * methods; and constant time for the retrieval methods
74   * ({@code peek}, {@code element}, and {@code size}).
75   *
76   * <p>This class is a member of the
77 < * <a href="{@docRoot}/../technotes/guides/collections/index.html">
77 > * <a href="{@docRoot}/java/util/package-summary.html#CollectionsFramework">
78   * Java Collections Framework</a>.
79   *
80   * @since 1.5
81   * @author Josh Bloch, Doug Lea
82 < * @param <E> the type of elements held in this collection
82 > * @param <E> the type of elements held in this queue
83   */
84   public class PriorityQueue<E> extends AbstractQueue<E>
85      implements java.io.Serializable {
# Line 101 | Line 101 | public class PriorityQueue<E> extends Ab
101      /**
102       * The number of elements in the priority queue.
103       */
104 <    private int size = 0;
104 >    int size;
105  
106      /**
107       * The comparator, or null if priority queue uses elements'
# Line 113 | Line 113 | public class PriorityQueue<E> extends Ab
113       * The number of times this priority queue has been
114       * <i>structurally modified</i>.  See AbstractList for gory details.
115       */
116 <    transient int modCount = 0; // non-private to simplify nested class access
116 >    transient int modCount;     // non-private to simplify nested class access
117  
118      /**
119       * Creates a {@code PriorityQueue} with the default initial
# Line 138 | Line 138 | public class PriorityQueue<E> extends Ab
138      }
139  
140      /**
141 +     * Creates a {@code PriorityQueue} with the default initial capacity and
142 +     * whose elements are ordered according to the specified comparator.
143 +     *
144 +     * @param  comparator the comparator that will be used to order this
145 +     *         priority queue.  If {@code null}, the {@linkplain Comparable
146 +     *         natural ordering} of the elements will be used.
147 +     * @since 1.8
148 +     */
149 +    public PriorityQueue(Comparator<? super E> comparator) {
150 +        this(DEFAULT_INITIAL_CAPACITY, comparator);
151 +    }
152 +
153 +    /**
154       * Creates a {@code PriorityQueue} with the specified initial capacity
155       * that orders its elements according to the specified comparator.
156       *
# Line 247 | Line 260 | public class PriorityQueue<E> extends Ab
260              a = Arrays.copyOf(a, a.length, Object[].class);
261          int len = a.length;
262          if (len == 1 || this.comparator != null)
263 <            for (int i = 0; i < len; i++)
264 <                if (a[i] == null)
263 >            for (Object e : a)
264 >                if (e == null)
265                      throw new NullPointerException();
266          this.queue = a;
267          this.size = a.length;
# Line 326 | Line 339 | public class PriorityQueue<E> extends Ab
339          int i = size;
340          if (i >= queue.length)
341              grow(i + 1);
342 +        siftUp(i, e);
343          size = i + 1;
330        if (i == 0)
331            queue[0] = e;
332        else
333            siftUp(i, e);
344          return true;
345      }
346  
# Line 341 | Line 351 | public class PriorityQueue<E> extends Ab
351  
352      private int indexOf(Object o) {
353          if (o != null) {
354 <            for (int i = 0; i < size; i++)
355 <                if (o.equals(queue[i]))
354 >            final Object[] es = queue;
355 >            for (int i = 0, n = size; i < n; i++)
356 >                if (o.equals(es[i]))
357                      return i;
358          }
359          return -1;
# Line 370 | Line 381 | public class PriorityQueue<E> extends Ab
381      }
382  
383      /**
384 <     * Version of remove using reference equality, not equals.
374 <     * Needed by iterator.remove.
384 >     * Identity-based version for use in Itr.remove.
385       *
386       * @param o element to be removed from this queue, if present
377     * @return {@code true} if removed
387       */
388 <    boolean removeEq(Object o) {
389 <        for (int i = 0; i < size; i++) {
390 <            if (o == queue[i]) {
388 >    void removeEq(Object o) {
389 >        final Object[] es = queue;
390 >        for (int i = 0, n = size; i < n; i++) {
391 >            if (o == es[i]) {
392                  removeAt(i);
393 <                return true;
393 >                break;
394              }
395          }
386        return false;
396      }
397  
398      /**
# Line 395 | Line 404 | public class PriorityQueue<E> extends Ab
404       * @return {@code true} if this queue contains the specified element
405       */
406      public boolean contains(Object o) {
407 <        return indexOf(o) != -1;
407 >        return indexOf(o) >= 0;
408      }
409  
410      /**
# Line 437 | Line 446 | public class PriorityQueue<E> extends Ab
446       * The following code can be used to dump the queue into a newly
447       * allocated array of {@code String}:
448       *
449 <     *  <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
449 >     * <pre> {@code String[] y = x.toArray(new String[0]);}</pre>
450       *
451       * Note that {@code toArray(new Object[0])} is identical in function to
452       * {@code toArray()}.
# Line 453 | Line 462 | public class PriorityQueue<E> extends Ab
462       */
463      @SuppressWarnings("unchecked")
464      public <T> T[] toArray(T[] a) {
465 +        final int size = this.size;
466          if (a.length < size)
467              // Make a new array of a's runtime type, but my contents:
468              return (T[]) Arrays.copyOf(queue, size, a.getClass());
# Line 477 | Line 487 | public class PriorityQueue<E> extends Ab
487           * Index (into queue array) of element to be returned by
488           * subsequent call to next.
489           */
490 <        private int cursor = 0;
490 >        private int cursor;
491  
492          /**
493           * Index of element returned by most recent call to next,
# Line 497 | Line 507 | public class PriorityQueue<E> extends Ab
507           * We expect that most iterations, even those involving removals,
508           * will not need to store elements in this field.
509           */
510 <        private ArrayDeque<E> forgetMeNot = null;
510 >        private ArrayDeque<E> forgetMeNot;
511  
512          /**
513           * Element returned by the most recent call to next iff that
514           * element was drawn from the forgetMeNot list.
515           */
516 <        private E lastRetElt = null;
516 >        private E lastRetElt;
517  
518          /**
519           * The modCount value that the iterator believes that the backing
# Line 512 | Line 522 | public class PriorityQueue<E> extends Ab
522           */
523          private int expectedModCount = modCount;
524  
525 +        Itr() {}                        // prevent access constructor creation
526 +
527          public boolean hasNext() {
528              return cursor < size ||
529                  (forgetMeNot != null && !forgetMeNot.isEmpty());
# Line 542 | Line 554 | public class PriorityQueue<E> extends Ab
554                      cursor--;
555                  else {
556                      if (forgetMeNot == null)
557 <                        forgetMeNot = new ArrayDeque<E>();
557 >                        forgetMeNot = new ArrayDeque<>();
558                      forgetMeNot.add(moved);
559                  }
560              } else if (lastRetElt != null) {
# Line 565 | Line 577 | public class PriorityQueue<E> extends Ab
577       */
578      public void clear() {
579          modCount++;
580 <        for (int i = 0; i < size; i++)
581 <            queue[i] = null;
580 >        final Object[] es = queue;
581 >        for (int i = 0, n = size; i < n; i++)
582 >            es[i] = null;
583          size = 0;
584      }
585  
# Line 597 | Line 610 | public class PriorityQueue<E> extends Ab
610       * avoid missing traversing elements.
611       */
612      @SuppressWarnings("unchecked")
613 <    private E removeAt(int i) {
613 >    E removeAt(int i) {
614          // assert i >= 0 && i < size;
615          modCount++;
616          int s = --size;
# Line 621 | Line 634 | public class PriorityQueue<E> extends Ab
634       * promoting x up the tree until it is greater than or equal to
635       * its parent, or is the root.
636       *
637 <     * To simplify and speed up coercions and comparisons. the
637 >     * To simplify and speed up coercions and comparisons, the
638       * Comparable and Comparator versions are separated into different
639       * methods that are otherwise identical. (Similarly for siftDown.)
640       *
# Line 717 | Line 730 | public class PriorityQueue<E> extends Ab
730      /**
731       * Establishes the heap invariant (described above) in the entire tree,
732       * assuming nothing about the order of the elements prior to the call.
733 +     * This classic algorithm due to Floyd (1964) is known to be O(size).
734       */
735      @SuppressWarnings("unchecked")
736      private void heapify() {
737 <        for (int i = (size >>> 1) - 1; i >= 0; i--)
738 <            siftDown(i, (E) queue[i]);
737 >        final Object[] es = queue;
738 >        int i = (size >>> 1) - 1;
739 >        if (comparator == null)
740 >            for (; i >= 0; i--)
741 >                siftDownComparable(i, (E) es[i]);
742 >        else
743 >            for (; i >= 0; i--)
744 >                siftDownUsingComparator(i, (E) es[i]);
745      }
746  
747      /**
# Line 740 | Line 760 | public class PriorityQueue<E> extends Ab
760      /**
761       * Saves this queue to a stream (that is, serializes it).
762       *
763 +     * @param s the stream
764 +     * @throws java.io.IOException if an I/O error occurs
765       * @serialData The length of the array backing the instance is
766       *             emitted (int), followed by all of its elements
767       *             (each an {@code Object}) in the proper order.
746     * @param s the stream
768       */
769      private void writeObject(java.io.ObjectOutputStream s)
770          throws java.io.IOException {
# Line 754 | Line 775 | public class PriorityQueue<E> extends Ab
775          s.writeInt(Math.max(2, size + 1));
776  
777          // Write out all elements in the "proper order".
778 <        for (int i = 0; i < size; i++)
779 <            s.writeObject(queue[i]);
778 >        final Object[] es = queue;
779 >        for (int i = 0, n = size; i < n; i++)
780 >            s.writeObject(es[i]);
781      }
782  
783      /**
# Line 763 | Line 785 | public class PriorityQueue<E> extends Ab
785       * (that is, deserializes it).
786       *
787       * @param s the stream
788 +     * @throws ClassNotFoundException if the class of a serialized object
789 +     *         could not be found
790 +     * @throws java.io.IOException if an I/O error occurs
791       */
792      private void readObject(java.io.ObjectInputStream s)
793          throws java.io.IOException, ClassNotFoundException {
# Line 772 | Line 797 | public class PriorityQueue<E> extends Ab
797          // Read in (and discard) array length
798          s.readInt();
799  
800 +        SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size);
801          queue = new Object[size];
802  
803          // Read in all elements.
804 <        for (int i = 0; i < size; i++)
805 <            queue[i] = s.readObject();
804 >        final Object[] es = queue;
805 >        for (int i = 0, n = size; i < n; i++)
806 >            es[i] = s.readObject();
807  
808          // Elements are guaranteed to be in "proper order", but the
809          // spec has never explained what that might be.
810          heapify();
811      }
812  
813 <    // wrapping constructor in method avoids transient javac problems
814 <    final PriorityQueueSpliterator<E> spliterator(int origin, int fence,
815 <                                                  int expectedModCount) {
816 <        return new PriorityQueueSpliterator<E>(this, origin, fence,
817 <                                               expectedModCount);
818 <    }
819 <
820 <    public Stream<E> stream() {
821 <        int flags = Streams.STREAM_IS_SIZED;
822 <        return Streams.stream
823 <            (() -> spliterator(0, size, modCount), flags);
824 <    }
825 <    public Stream<E> parallelStream() {
826 <        int flags = Streams.STREAM_IS_SIZED;
827 <        return Streams.parallelStream
828 <            (() -> spliterator(0, size, modCount), flags);
829 <    }
830 <
831 <    /** Index-based split-by-two Spliterator */
832 <    static final class PriorityQueueSpliterator<E>
833 <        implements Spliterator<E>, Iterator<E> {
834 <        private final PriorityQueue<E> pq;
835 <        private int index;           // current index, modified on advance/split
836 <        private final int fence;     // one past last index
837 <        private final int expectedModCount; // for comodification checks
838 <
839 <        /** Create new spliterator covering the given  range */
813 <        PriorityQueueSpliterator(PriorityQueue<E> pq, int origin, int fence,
814 <                             int expectedModCount) {
815 <            this.pq = pq; this.index = origin; this.fence = fence;
813 >    /**
814 >     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
815 >     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
816 >     * queue. The spliterator does not traverse elements in any particular order
817 >     * (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported).
818 >     *
819 >     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED},
820 >     * {@link Spliterator#SUBSIZED}, and {@link Spliterator#NONNULL}.
821 >     * Overriding implementations should document the reporting of additional
822 >     * characteristic values.
823 >     *
824 >     * @return a {@code Spliterator} over the elements in this queue
825 >     * @since 1.8
826 >     */
827 >    public final Spliterator<E> spliterator() {
828 >        return new PriorityQueueSpliterator(0, -1, 0);
829 >    }
830 >
831 >    final class PriorityQueueSpliterator implements Spliterator<E> {
832 >        private int index;            // current index, modified on advance/split
833 >        private int fence;            // -1 until first use
834 >        private int expectedModCount; // initialized when fence set
835 >
836 >        /** Creates new spliterator covering the given range. */
837 >        PriorityQueueSpliterator(int origin, int fence, int expectedModCount) {
838 >            this.index = origin;
839 >            this.fence = fence;
840              this.expectedModCount = expectedModCount;
841          }
842  
843 <        public PriorityQueueSpliterator<E> trySplit() {
844 <            int lo = index, mid = (lo + fence) >>> 1;
843 >        private int getFence() { // initialize fence to size on first use
844 >            int hi;
845 >            if ((hi = fence) < 0) {
846 >                expectedModCount = modCount;
847 >                hi = fence = size;
848 >            }
849 >            return hi;
850 >        }
851 >
852 >        public PriorityQueueSpliterator trySplit() {
853 >            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
854              return (lo >= mid) ? null :
855 <                new PriorityQueueSpliterator<E>(pq, lo, index = mid,
823 <                                            expectedModCount);
855 >                new PriorityQueueSpliterator(lo, index = mid, expectedModCount);
856          }
857  
858 <        public void forEach(Block<? super E> block) {
859 <            Object[] a; int i, hi; // hoist accesses and checks from loop
860 <            if (block == null)
858 >        @SuppressWarnings("unchecked")
859 >        public void forEachRemaining(Consumer<? super E> action) {
860 >            if (action == null)
861                  throw new NullPointerException();
862 <            if ((a = pq.queue).length >= (hi = fence) &&
863 <                (i = index) >= 0 && i < hi) {
864 <                index = hi;
865 <                do {
866 <                    @SuppressWarnings("unchecked") E e = (E) a[i];
867 <                    block.accept(e);
868 <                } while (++i < hi);
837 <                if (pq.modCount != expectedModCount)
838 <                    throw new ConcurrentModificationException();
862 >            if (fence < 0) { fence = size; expectedModCount = modCount; }
863 >            final Object[] a = queue;
864 >            int i, hi; E e;
865 >            for (i = index, index = hi = fence; i < hi; i++) {
866 >                if ((e = (E) a[i]) == null)
867 >                    break;      // must be CME
868 >                action.accept(e);
869              }
870 +            if (modCount != expectedModCount)
871 +                throw new ConcurrentModificationException();
872          }
873  
874 <        public boolean tryAdvance(Block<? super E> block) {
875 <            if (index >= 0 && index < fence) {
876 <                if (pq.modCount != expectedModCount)
874 >        @SuppressWarnings("unchecked")
875 >        public boolean tryAdvance(Consumer<? super E> action) {
876 >            if (action == null)
877 >                throw new NullPointerException();
878 >            if (fence < 0) { fence = size; expectedModCount = modCount; }
879 >            int i;
880 >            if ((i = index) < fence) {
881 >                index = i + 1;
882 >                E e;
883 >                if ((e = (E) queue[i]) == null
884 >                    || modCount != expectedModCount)
885                      throw new ConcurrentModificationException();
886 <                @SuppressWarnings("unchecked") E e =
847 <                    (E)pq.queue[index++];
848 <                block.accept(e);
886 >                action.accept(e);
887                  return true;
888              }
889              return false;
890          }
891  
892 <        public long estimateSize() { return (long)(fence - index); }
893 <        public boolean hasExactSize() { return true; }
894 <        public boolean hasExactSplits() { return true; }
857 <
858 <        // Iterator support
859 <        public Iterator<E> iterator() { return this; }
860 <        public void remove() { throw new UnsupportedOperationException(); }
861 <        public boolean hasNext() { return index >= 0 && index < fence; }
892 >        public long estimateSize() {
893 >            return getFence() - index;
894 >        }
895  
896 <        public E next() {
897 <            if (index < 0 || index >= fence)
865 <                throw new NoSuchElementException();
866 <            if (pq.modCount != expectedModCount)
867 <                throw new ConcurrentModificationException();
868 <            @SuppressWarnings("unchecked") E e =
869 <                (E) pq.queue[index++];
870 <            return e;
896 >        public int characteristics() {
897 >            return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.NONNULL;
898          }
899      }
900 +
901 +    /**
902 +     * @throws NullPointerException {@inheritDoc}
903 +     */
904 +    @SuppressWarnings("unchecked")
905 +    public void forEach(Consumer<? super E> action) {
906 +        Objects.requireNonNull(action);
907 +        final int expectedModCount = modCount;
908 +        final Object[] es = queue;
909 +        for (int i = 0, n = size; i < n; i++)
910 +            action.accept((E) es[i]);
911 +        if (expectedModCount != modCount)
912 +            throw new ConcurrentModificationException();
913 +    }
914   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines