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.23 by dholmes, Wed Aug 6 01:57:53 2003 UTC vs.
Revision 1.45 by dl, Sun Oct 19 13:38:29 2003 UTC

# Line 1 | Line 1
1 < package java.util;
1 > /*
2 > * %W% %E%
3 > *
4 > * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
5 > * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6 > */
7 >
8 > package java.util;
9  
10   /**
11 < * An unbounded priority {@linkplain Queue queue} based on a priority heap.  
12 < * This queue orders
13 < * elements according to an order specified at construction time, which is
14 < * specified in the same manner as {@link java.util.TreeSet} and
15 < * {@link java.util.TreeMap}: elements are ordered
16 < * either according to their <i>natural order</i> (see {@link Comparable}), or
17 < * according to a {@link java.util.Comparator}, depending on which
18 < * constructor is used.
19 < * <p>The <em>head</em> of this queue is the <em>least</em> element with
20 < * respect to the specified ordering.
21 < * If multiple elements are tied for least value, the
22 < * head is one of those elements. A priority queue does not permit
23 < * <tt>null</tt> elements.
11 > * An unbounded priority {@linkplain Queue queue} based on a priority
12 > * heap.  This queue orders elements according to an order specified
13 > * at construction time, which is specified either according to their
14 > * <i>natural order</i> (see {@link Comparable}), or according to a
15 > * {@link java.util.Comparator}, depending on which constructor is
16 > * used. A priority queue does not permit <tt>null</tt> elements.
17 > * A priority queue relying on natural ordering also does not
18 > * permit insertion of non-comparable objects (doing so may result
19 > * in <tt>ClassCastException</tt>).
20 > *
21 > * <p>The <em>head</em> of this queue is the <em>least</em> element
22 > * with respect to the specified ordering.  If multiple elements are
23 > * tied for least value, the head is one of those elements -- ties are
24 > * broken arbitrarily.  The queue retrieval operations <tt>poll</tt>,
25 > * <tt>remove</tt>, <tt>peek</tt>, and <tt>element</tt> access the
26 > * element at the head of the queue.
27   *
28 < * <p>The {@link #remove()} and {@link #poll()} methods remove and
29 < * return the head of the queue.
28 > * <p>A priority queue is unbounded, but has an internal
29 > * <i>capacity</i> governing the size of an array used to store the
30 > * elements on the queue.  It is always at least as large as the queue
31 > * size.  As elements are added to a priority queue, its capacity
32 > * grows automatically.  The details of the growth policy are not
33 > * specified.
34   *
35 < * <p>The {@link #element()} and {@link #peek()} methods return, but do
36 < * not delete, the head of the queue.
35 > * <p>This class implements all of the <em>optional</em> methods of
36 > * the {@link Collection} and {@link Iterator} interfaces.  The
37 > * Iterator provided in method {@link #iterator()} is <em>not</em>
38 > * guaranteed to traverse the elements of the PriorityQueue in any
39 > * particular order. If you need ordered traversal, consider using
40 > * <tt>Arrays.sort(pq.toArray())</tt>.
41   *
42 < * <p>A priority queue has a <i>capacity</i>.  The capacity is the
43 < * size of the array used internally to store the elements on the
44 < * queue.
45 < * It is always at least as large as the queue size.  As
46 < * elements are added to a priority queue, its capacity grows
29 < * automatically.  The details of the growth policy are not specified.
42 > * <p> <strong>Note that this implementation is not synchronized.</strong>
43 > * Multiple threads should not access a <tt>PriorityQueue</tt>
44 > * instance concurrently if any of the threads modifies the list
45 > * structurally. Instead, use the thread-safe {@link
46 > * java.util.concurrent.PriorityBlockingQueue} class.
47   *
48 + *
49   * <p>Implementation note: this implementation provides O(log(n)) time
50   * for the insertion methods (<tt>offer</tt>, <tt>poll</tt>,
51   * <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the
# Line 39 | Line 57
57   * <a href="{@docRoot}/../guide/collections/index.html">
58   * Java Collections Framework</a>.
59   * @since 1.5
60 + * @version %I%, %G%
61   * @author Josh Bloch
62 + * @param <E> the type of elements held in this collection
63   */
64   public class PriorityQueue<E> extends AbstractQueue<E>
65      implements Queue<E>, java.io.Serializable {
66  
67 +    private static final long serialVersionUID = -7720805057305804111L;
68 +
69      private static final int DEFAULT_INITIAL_CAPACITY = 11;
70  
71      /**
# Line 81 | Line 103 | public class PriorityQueue<E> extends Ab
103      /**
104       * Creates a <tt>PriorityQueue</tt> with the default initial capacity
105       * (11) that orders its elements according to their natural
106 <     * ordering (using <tt>Comparable</tt>.)
106 >     * ordering (using <tt>Comparable</tt>).
107       */
108      public PriorityQueue() {
109          this(DEFAULT_INITIAL_CAPACITY, null);
# Line 90 | Line 112 | public class PriorityQueue<E> extends Ab
112      /**
113       * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
114       * that orders its elements according to their natural ordering
115 <     * (using <tt>Comparable</tt>.)
115 >     * (using <tt>Comparable</tt>).
116       *
117       * @param initialCapacity the initial capacity for this priority queue.
118       * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
# Line 136 | Line 158 | public class PriorityQueue<E> extends Ab
158      /**
159       * Initially fill elements of the queue array under the
160       * knowledge that it is sorted or is another PQ, in which
161 <     * case we can just place the elements without fixups.
161 >     * case we can just place the elements in the order presented.
162       */
163      private void fillFromSorted(Collection<? extends E> c) {
164          for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
165              queue[++size] = i.next();
166      }
167  
146
168      /**
169 <     * Initially fill elements of the queue array that is
170 <     * not to our knowledge sorted, so we must add them
171 <     * one by one.
169 >     * Initially fill elements of the queue array that is not to our knowledge
170 >     * sorted, so we must rearrange the elements to guarantee the heap
171 >     * invariant.
172       */
173      private void fillFromUnsorted(Collection<? extends E> c) {
174          for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
175 <            add(i.next());
175 >            queue[++size] = i.next();
176 >        heapify();
177      }
178  
179      /**
# Line 159 | Line 181 | public class PriorityQueue<E> extends Ab
181       * specified collection.  The priority queue has an initial
182       * capacity of 110% of the size of the specified collection or 1
183       * if the collection is empty.  If the specified collection is an
184 <     * instance of a {@link SortedSet} or is another
184 >     * instance of a {@link java.util.SortedSet} or is another
185       * <tt>PriorityQueue</tt>, the priority queue will be sorted
186       * according to the same comparator, or according to its elements'
187       * natural order if the collection is sorted according to its
# Line 176 | Line 198 | public class PriorityQueue<E> extends Ab
198       */
199      public PriorityQueue(Collection<? extends E> c) {
200          initializeArray(c);
201 <        if (c instanceof SortedSet<? extends E>) {
202 <            SortedSet<? extends E> s = (SortedSet<? extends E>) c;
201 >        if (c instanceof SortedSet) {
202 >            // @fixme double-cast workaround for compiler
203 >            SortedSet<? extends E> s = (SortedSet<? extends E>) (SortedSet)c;
204              comparator = (Comparator<? super E>)s.comparator();
205              fillFromSorted(s);
206 <        }
184 <        else if (c instanceof PriorityQueue<? extends E>) {
206 >        } else if (c instanceof PriorityQueue) {
207              PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c;
208              comparator = (Comparator<? super E>)s.comparator();
209              fillFromSorted(s);
210 <        }
189 <        else {
210 >        } else {
211              comparator = null;
212              fillFromUnsorted(c);
213          }
# Line 258 | Line 279 | public class PriorityQueue<E> extends Ab
279          queue = newQueue;
280      }
281              
261    // Queue Methods
262
263
282  
283      /**
284 <     * Add the specified element to this priority queue.
284 >     * Inserts the specified element into this priority queue.
285       *
286       * @return <tt>true</tt>
287       * @throws ClassCastException if the specified element cannot be compared
# Line 286 | Line 304 | public class PriorityQueue<E> extends Ab
304          return true;
305      }
306  
307 <    public E poll() {
307 >    public E peek() {
308          if (size == 0)
309              return null;
292        return (E) remove(1);
293    }
294
295    public E peek() {
310          return (E) queue[1];
311      }
312  
# Line 303 | Line 317 | public class PriorityQueue<E> extends Ab
317       * @return <tt>true</tt> (as per the general contract of
318       * <tt>Collection.add</tt>).
319       *
320 <     * @throws NullPointerException {@inheritDoc}
320 >     * @throws NullPointerException if the specified element is <tt>null</tt>.
321       * @throws ClassCastException if the specified element cannot be compared
322       * with elements currently in the priority queue according
323       * to the priority queue's ordering.
324       */
325      public boolean add(E o) {
326 <        return super.add(o);
313 <    }
314 <
315 <  
316 <    /**
317 <     * Adds all of the elements in the specified collection to this queue.
318 <     * The behavior of this operation is undefined if
319 <     * the specified collection is modified while the operation is in
320 <     * progress.  (This implies that the behavior of this call is undefined if
321 <     * the specified collection is this queue, and this queue is nonempty.)
322 <     * <p>
323 <     * This implementation iterates over the specified collection, and adds
324 <     * each object returned by the iterator to this collection, in turn.
325 <     * @throws NullPointerException {@inheritDoc}
326 <     * @throws ClassCastException if any element cannot be compared
327 <     * with elements currently in the priority queue according
328 <     * to the priority queue's ordering.
329 <     */
330 <    public boolean addAll(Collection<? extends E> c) {
331 <        return super.addAll(c);
326 >        return offer(o);
327      }
328  
334
335 /**
336     * Removes a single instance of the specified element from this
337     * queue, if it is present.  More formally,
338     * removes an element <tt>e</tt> such that <tt>(o==null ? e==null :
339     * o.equals(e))</tt>, if the queue contains one or more such
340     * elements.  Returns <tt>true</tt> if the queue contained the
341     * specified element (or equivalently, if the queue changed as a
342     * result of the call).
343     *
344     * <p>This implementation iterates over the queue looking for the
345     * specified element.  If it finds the element, it removes the element
346     * from the queue using the iterator's remove method.<p>
347     *
348     */
329      public boolean remove(Object o) {
330          if (o == null)
331              return false;
# Line 353 | Line 333 | public class PriorityQueue<E> extends Ab
333          if (comparator == null) {
334              for (int i = 1; i <= size; i++) {
335                  if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
336 <                    remove(i);
336 >                    removeAt(i);
337                      return true;
338                  }
339              }
340          } else {
341              for (int i = 1; i <= size; i++) {
342                  if (comparator.compare((E)queue[i], (E)o) == 0) {
343 <                    remove(i);
343 >                    removeAt(i);
344                      return true;
345                  }
346              }
# Line 379 | Line 359 | public class PriorityQueue<E> extends Ab
359      }
360  
361      private class Itr implements Iterator<E> {
362 +
363          /**
364           * Index (into queue array) of element to be returned by
365           * subsequent call to next.
# Line 386 | Line 367 | public class PriorityQueue<E> extends Ab
367          private int cursor = 1;
368  
369          /**
370 <         * Index of element returned by most recent call to next or
371 <         * previous.  Reset to 0 if this element is deleted by a call
372 <         * to remove.
370 >         * Index of element returned by most recent call to next,
371 >         * unless that element came from the forgetMeNot list.
372 >         * Reset to 0 if element is deleted by a call to remove.
373           */
374          private int lastRet = 0;
375  
# Line 399 | Line 380 | public class PriorityQueue<E> extends Ab
380           */
381          private int expectedModCount = modCount;
382  
383 +        /**
384 +         * A list of elements that were moved from the unvisited portion of
385 +         * the heap into the visited portion as a result of "unlucky" element
386 +         * removals during the iteration.  (Unlucky element removals are those
387 +         * that require a fixup instead of a fixdown.)  We must visit all of
388 +         * the elements in this list to complete the iteration.  We do this
389 +         * after we've completed the "normal" iteration.
390 +         *
391 +         * We expect that most iterations, even those involving removals,
392 +         * will not use need to store elements in this field.
393 +         */
394 +        private ArrayList<E> forgetMeNot = null;
395 +
396 +        /**
397 +         * Element returned by the most recent call to next iff that
398 +         * element was drawn from the forgetMeNot list.
399 +         */
400 +        private Object lastRetElt = null;
401 +
402          public boolean hasNext() {
403 <            return cursor <= size;
403 >            return cursor <= size || forgetMeNot != null;
404          }
405  
406          public E next() {
407              checkForComodification();
408 <            if (cursor > size)
408 >            E result;
409 >            if (cursor <= size) {
410 >                result = (E) queue[cursor];
411 >                lastRet = cursor++;
412 >            }
413 >            else if (forgetMeNot == null)
414                  throw new NoSuchElementException();
415 <            E result = (E) queue[cursor];
416 <            lastRet = cursor++;
415 >            else {
416 >                int remaining = forgetMeNot.size();
417 >                result = forgetMeNot.remove(remaining - 1);
418 >                if (remaining == 1)
419 >                    forgetMeNot = null;
420 >                lastRet = 0;
421 >                lastRetElt = result;
422 >            }
423              return result;
424          }
425  
426          public void remove() {
416            if (lastRet == 0)
417                throw new IllegalStateException();
427              checkForComodification();
428  
429 <            PriorityQueue.this.remove(lastRet);
430 <            if (lastRet < cursor)
431 <                cursor--;
432 <            lastRet = 0;
429 >            if (lastRet != 0) {
430 >                E moved = PriorityQueue.this.removeAt(lastRet);
431 >                lastRet = 0;
432 >                if (moved == null) {
433 >                    cursor--;
434 >                } else {
435 >                    if (forgetMeNot == null)
436 >                        forgetMeNot = new ArrayList<E>();
437 >                    forgetMeNot.add(moved);
438 >                }
439 >            } else if (lastRetElt != null) {
440 >                PriorityQueue.this.remove(lastRetElt);
441 >                lastRetElt = null;
442 >            } else {
443 >                throw new IllegalStateException();
444 >            }
445 >
446              expectedModCount = modCount;
447          }
448  
# Line 447 | Line 469 | public class PriorityQueue<E> extends Ab
469          size = 0;
470      }
471  
472 +    public E poll() {
473 +        if (size == 0)
474 +            return null;
475 +        modCount++;
476 +
477 +        E result = (E) queue[1];
478 +        queue[1] = queue[size];
479 +        queue[size--] = null;  // Drop extra ref to prevent memory leak
480 +        if (size > 1)
481 +            fixDown(1);
482 +
483 +        return result;
484 +    }
485 +
486      /**
487 <     * Removes and returns the ith element from queue.  Recall
488 <     * that queue is one-based, so 1 <= i <= size.
487 >     * Removes and returns the ith element from queue.  (Recall that queue
488 >     * is one-based, so 1 <= i <= size.)
489       *
490 <     * XXX: Could further special-case i==size, but is it worth it?
491 <     * XXX: Could special-case i==0, but is it worth it?
490 >     * Normally this method leaves the elements at positions from 1 up to i-1,
491 >     * inclusive, untouched.  Under these circumstances, it returns null.
492 >     * Occasionally, in order to maintain the heap invariant, it must move
493 >     * the last element of the list to some index in the range [2, i-1],
494 >     * and move the element previously at position (i/2) to position i.
495 >     * Under these circumstances, this method returns the element that was
496 >     * previously at the end of the list and is now at some position between
497 >     * 2 and i-1 inclusive.
498       */
499 <    private E remove(int i) {
500 <        assert i <= size;
499 >    private E removeAt(int i) {
500 >        assert i > 0 && i <= size;
501          modCount++;
502  
503 <        E result = (E) queue[i];
504 <        queue[i] = queue[size];
503 >        E moved = (E) queue[size];
504 >        queue[i] = moved;
505          queue[size--] = null;  // Drop extra ref to prevent memory leak
506 <        if (i <= size)
506 >        if (i <= size) {
507              fixDown(i);
508 <        return result;
508 >            if (queue[i] == moved) {
509 >                fixUp(i);
510 >                if (queue[i] != moved)
511 >                    return moved;
512 >            }
513 >        }
514 >        return null;
515      }
516  
517      /**
# Line 486 | Line 534 | public class PriorityQueue<E> extends Ab
534              }
535          } else {
536              while (k > 1) {
537 <                int j = k >> 1;
537 >                int j = k >>> 1;
538                  if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
539                      break;
540                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
# Line 507 | Line 555 | public class PriorityQueue<E> extends Ab
555      private void fixDown(int k) {
556          int j;
557          if (comparator == null) {
558 <            while ((j = k << 1) <= size) {
559 <                if (j<size && ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
558 >            while ((j = k << 1) <= size && (j > 0)) {
559 >                if (j<size &&
560 >                    ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
561                      j++; // j indexes smallest kid
562 +
563                  if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
564                      break;
565                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
566                  k = j;
567              }
568          } else {
569 <            while ((j = k << 1) <= size) {
570 <                if (j < size && comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
569 >            while ((j = k << 1) <= size && (j > 0)) {
570 >                if (j<size &&
571 >                    comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
572                      j++; // j indexes smallest kid
573                  if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
574                      break;
# Line 527 | Line 578 | public class PriorityQueue<E> extends Ab
578          }
579      }
580  
581 +    /**
582 +     * Establishes the heap invariant (described above) in the entire tree,
583 +     * assuming nothing about the order of the elements prior to the call.
584 +     */
585 +    private void heapify() {
586 +        for (int i = size/2; i >= 1; i--)
587 +            fixDown(i);
588 +    }
589  
590      /**
591       * Returns the comparator used to order this collection, or <tt>null</tt>
592       * if this collection is sorted according to its elements natural ordering
593 <     * (using <tt>Comparable</tt>.)
593 >     * (using <tt>Comparable</tt>).
594       *
595       * @return the comparator used to order this collection, or <tt>null</tt>
596       * if this collection is sorted according to its elements natural ordering.
# Line 558 | Line 617 | public class PriorityQueue<E> extends Ab
617          s.writeInt(queue.length);
618  
619          // Write out all elements in the proper order.
620 <        for (int i=0; i<size; i++)
620 >        for (int i=1; i<=size; i++)
621              s.writeObject(queue[i]);
622      }
623  
# Line 577 | Line 636 | public class PriorityQueue<E> extends Ab
636          queue = new Object[arrayLength];
637  
638          // Read in all elements in the proper order.
639 <        for (int i=0; i<size; i++)
640 <            queue[i] = s.readObject();
639 >        for (int i=1; i<=size; i++)
640 >            queue[i] = (E) s.readObject();
641      }
642  
643   }
585

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines