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.32 by dl, Mon Aug 25 23:47:01 2003 UTC vs.
Revision 1.40 by dl, Fri Sep 12 15:38:26 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
11 < * constructor is used.
11 > * An unbounded priority {@linkplain Queue queue} based on a priority heap.
12 > * This queue orders elements according to an order specified at construction
13 > * time, which is specified in the same manner as {@link java.util.TreeSet}
14 > * and {@link java.util.TreeMap}: elements are ordered either according to
15 > * their <i>natural order</i> (see {@link Comparable}), or according to a
16 > * {@link java.util.Comparator}, depending on which constructor is used.
17 > *
18   * <p>The <em>head</em> of this queue is the <em>least</em> element with
19 < * respect to the specified ordering.
20 < * If multiple elements are tied for least value, the
21 < * head is one of those elements. A priority queue does not permit
16 < * <tt>null</tt> elements.
19 > * respect to the specified ordering.  If multiple elements are tied for least
20 > * value, the head is one of those elements. A priority queue does not permit
21 > * <tt>null</tt> elements.
22   *
23   * <p>The {@link #remove()} and {@link #poll()} methods remove and
24   * return the head of the queue.
# Line 21 | Line 26
26   * <p>The {@link #element()} and {@link #peek()} methods return, but do
27   * not delete, the head of the queue.
28   *
29 < * <p>A priority queue has a <i>capacity</i>.  The capacity is the
30 < * size of the array used internally to store the elements on the
31 < * queue.
32 < * It is always at least as large as the queue size.  As
33 < * elements are added to a priority queue, its capacity grows
34 < * automatically.  The details of the growth policy are not specified.
29 > * <p>A priority queue is unbounded, but has a <i>capacity</i>.  The
30 > * capacity is the size of the array used internally to store the
31 > * elements on the queue.  It is always at least as large as the queue
32 > * size.  As elements are added to a priority queue, its capacity
33 > * grows automatically.  The details of the growth policy are not
34 > * specified.
35   *
36   * <p>The Iterator provided in method {@link #iterator()} is <em>not</em>
37   * guaranteed to traverse the elements of the PriorityQueue in any
# Line 37 | Line 42
42   * Multiple threads should not access a <tt>PriorityQueue</tt>
43   * instance concurrently if any of the threads modifies the list
44   * structurally. Instead, use the thread-safe {@link
45 < * java.util.concurrent.BlockingPriorityQueue} class.
45 > * java.util.concurrent.PriorityBlockingQueue} class.
46   *
47   *
48   * <p>Implementation note: this implementation provides O(log(n)) time
# Line 51 | Line 56
56   * <a href="{@docRoot}/../guide/collections/index.html">
57   * Java Collections Framework</a>.
58   * @since 1.5
59 + * @version %I%, %G%
60   * @author Josh Bloch
61   */
62   public class PriorityQueue<E> extends AbstractQueue<E>
# Line 150 | Line 156 | public class PriorityQueue<E> extends Ab
156      /**
157       * Initially fill elements of the queue array under the
158       * knowledge that it is sorted or is another PQ, in which
159 <     * case we can just place the elements without fixups.
159 >     * case we can just place the elements in the order presented.
160       */
161      private void fillFromSorted(Collection<? extends E> c) {
162          for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
163              queue[++size] = i.next();
164      }
165  
160
166      /**
167 <     * Initially fill elements of the queue array that is
168 <     * not to our knowledge sorted, so we must add them
169 <     * one by one.
167 >     * Initially fill elements of the queue array that is not to our knowledge
168 >     * sorted, so we must rearrange the elements to guarantee the heap
169 >     * invariant.
170       */
171      private void fillFromUnsorted(Collection<? extends E> c) {
172          for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
173 <            add(i.next());
173 >            queue[++size] = i.next();
174 >        heapify();
175      }
176  
177      /**
# Line 271 | Line 277 | public class PriorityQueue<E> extends Ab
277          queue = newQueue;
278      }
279              
274    // Queue Methods
275
276
280  
281      /**
282 <     * Add the specified element to this priority queue.
282 >     * Inserts the specified element to this priority queue.
283       *
284       * @return <tt>true</tt>
285       * @throws ClassCastException if the specified element cannot be compared
# Line 299 | Line 302 | public class PriorityQueue<E> extends Ab
302          return true;
303      }
304  
305 <    public E poll() {
305 >    public E peek() {
306          if (size == 0)
307              return null;
305        return (E) remove(1);
306    }
307
308    public E peek() {
308          return (E) queue[1];
309      }
310  
# Line 316 | Line 315 | public class PriorityQueue<E> extends Ab
315       * @return <tt>true</tt> (as per the general contract of
316       * <tt>Collection.add</tt>).
317       *
318 <     * @throws NullPointerException {@inheritDoc}
318 >     * @throws NullPointerException if the specified element is <tt>null</tt>.
319       * @throws ClassCastException if the specified element cannot be compared
320       * with elements currently in the priority queue according
321       * to the priority queue's ordering.
# Line 335 | Line 334 | public class PriorityQueue<E> extends Ab
334       * <p>
335       * This implementation iterates over the specified collection, and adds
336       * each object returned by the iterator to this collection, in turn.
337 <     * @throws NullPointerException {@inheritDoc}
337 >     * @param c collection whose elements are to be added to this queue
338 >     * @return <tt>true</tt> if this queue changed as a result of the
339 >     *         call.
340 >     * @throws NullPointerException if <tt>c</tt> or any element in <tt>c</tt>
341 >     * is <tt>null</tt>
342       * @throws ClassCastException if any element cannot be compared
343       * with elements currently in the priority queue according
344       * to the priority queue's ordering.
# Line 344 | Line 347 | public class PriorityQueue<E> extends Ab
347          return super.addAll(c);
348      }
349  
347
348 /**
349     * Removes a single instance of the specified element from this
350     * queue, if it is present.  More formally,
351     * removes an element <tt>e</tt> such that <tt>(o==null ? e==null :
352     * o.equals(e))</tt>, if the queue contains one or more such
353     * elements.  Returns <tt>true</tt> if the queue contained the
354     * specified element (or equivalently, if the queue changed as a
355     * result of the call).
356     *
357     * <p>This implementation iterates over the queue looking for the
358     * specified element.  If it finds the element, it removes the element
359     * from the queue using the iterator's remove method.<p>
360     *
361     */
350      public boolean remove(Object o) {
351          if (o == null)
352              return false;
# Line 366 | Line 354 | public class PriorityQueue<E> extends Ab
354          if (comparator == null) {
355              for (int i = 1; i <= size; i++) {
356                  if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
357 <                    remove(i);
357 >                    removeAt(i);
358                      return true;
359                  }
360              }
361          } else {
362              for (int i = 1; i <= size; i++) {
363                  if (comparator.compare((E)queue[i], (E)o) == 0) {
364 <                    remove(i);
364 >                    removeAt(i);
365                      return true;
366                  }
367              }
# Line 392 | Line 380 | public class PriorityQueue<E> extends Ab
380      }
381  
382      private class Itr implements Iterator<E> {
383 +
384          /**
385           * Index (into queue array) of element to be returned by
386           * subsequent call to next.
# Line 399 | Line 388 | public class PriorityQueue<E> extends Ab
388          private int cursor = 1;
389  
390          /**
391 <         * Index of element returned by most recent call to next or
392 <         * previous.  Reset to 0 if this element is deleted by a call
393 <         * to remove.
391 >         * Index of element returned by most recent call to next,
392 >         * unless that element came from the forgetMeNot list.
393 >         * Reset to 0 if element is deleted by a call to remove.
394           */
395          private int lastRet = 0;
396  
# Line 412 | Line 401 | public class PriorityQueue<E> extends Ab
401           */
402          private int expectedModCount = modCount;
403  
404 +        /**
405 +         * A list of elements that were moved from the unvisited portion of
406 +         * the heap into the visited portion as a result of "unlucky" element
407 +         * removals during the iteration.  (Unlucky element removals are those
408 +         * that require a fixup instead of a fixdown.)  We must visit all of
409 +         * the elements in this list to complete the iteration.  We do this
410 +         * after we've completed the "normal" iteration.
411 +         *
412 +         * We expect that most iterations, even those involving removals,
413 +         * will not use need to store elements in this field.
414 +         */
415 +        private ArrayList<E> forgetMeNot = null;
416 +
417 +        /**
418 +         * Element returned by the most recent call to next iff that
419 +         * element was drawn from the forgetMeNot list.
420 +         */
421 +        private Object lastRetElt = null;
422 +
423          public boolean hasNext() {
424 <            return cursor <= size;
424 >            return cursor <= size || forgetMeNot != null;
425          }
426  
427          public E next() {
428              checkForComodification();
429 <            if (cursor > size)
429 >            E result;
430 >            if (cursor <= size) {
431 >                result = (E) queue[cursor];
432 >                lastRet = cursor++;
433 >            }
434 >            else if (forgetMeNot == null)
435                  throw new NoSuchElementException();
436 <            E result = (E) queue[cursor];
437 <            lastRet = cursor++;
436 >            else {
437 >                int remaining = forgetMeNot.size();
438 >                result = forgetMeNot.remove(remaining - 1);
439 >                if (remaining == 1)
440 >                    forgetMeNot = null;
441 >                lastRet = 0;
442 >                lastRetElt = result;
443 >            }
444              return result;
445          }
446  
447          public void remove() {
429            if (lastRet == 0)
430                throw new IllegalStateException();
448              checkForComodification();
449  
450 <            PriorityQueue.this.remove(lastRet);
451 <            cursor--;
452 <            lastRet = 0;
450 >            if (lastRet != 0) {
451 >                E moved = PriorityQueue.this.removeAt(lastRet);
452 >                lastRet = 0;
453 >                if (moved == null) {
454 >                    cursor--;
455 >                } else {
456 >                    if (forgetMeNot == null)
457 >                        forgetMeNot = new ArrayList<E>();
458 >                    forgetMeNot.add(moved);
459 >                }
460 >            } else if (lastRetElt != null) {
461 >                PriorityQueue.this.remove(lastRetElt);
462 >                lastRetElt = null;
463 >            } else {
464 >                throw new IllegalStateException();
465 >            }
466 >
467              expectedModCount = modCount;
468          }
469  
# Line 459 | Line 490 | public class PriorityQueue<E> extends Ab
490          size = 0;
491      }
492  
493 +    public E poll() {
494 +        if (size == 0)
495 +            return null;
496 +        modCount++;
497 +
498 +        E result = (E) queue[1];
499 +        queue[1] = queue[size];
500 +        queue[size--] = null;  // Drop extra ref to prevent memory leak
501 +        if (size > 1)
502 +            fixDown(1);
503 +
504 +        return result;
505 +    }
506 +
507      /**
508 <     * Removes and returns the ith element from queue.  Recall
509 <     * that queue is one-based, so 1 <= i <= size.
508 >     * Removes and returns the ith element from queue.  (Recall that queue
509 >     * is one-based, so 1 <= i <= size.)
510       *
511 +     * Normally this method leaves the elements at positions from 1 up to i-1,
512 +     * inclusive, untouched.  Under these circumstances, it returns null.
513 +     * Occasionally, in order to maintain the heap invariant, it must move
514 +     * the last element of the list to some index in the range [2, i-1],
515 +     * and move the element previously at position (i/2) to position i.
516 +     * Under these circumstances, this method returns the element that was
517 +     * previously at the end of the list and is now at some position between
518 +     * 2 and i-1 inclusive.
519       */
520 <    private E remove(int i) {
521 <        assert i <= size;
520 >    private E removeAt(int i) {
521 >        assert i > 0 && i <= size;
522          modCount++;
523  
524 <        E result = (E) queue[i];
525 <        queue[i] = queue[size];
524 >        E moved = (E) queue[size];
525 >        queue[i] = moved;
526          queue[size--] = null;  // Drop extra ref to prevent memory leak
527 <        if (i <= size)
527 >        if (i <= size) {
528              fixDown(i);
529 <        return result;
529 >            if (queue[i] == moved) {
530 >                fixUp(i);
531 >                if (queue[i] != moved)
532 >                    return moved;
533 >            }
534 >        }
535 >        return null;
536      }
537  
538      /**
# Line 496 | Line 555 | public class PriorityQueue<E> extends Ab
555              }
556          } else {
557              while (k > 1) {
558 <                int j = k >> 1;
558 >                int j = k >>> 1;
559                  if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
560                      break;
561                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
# Line 517 | Line 576 | public class PriorityQueue<E> extends Ab
576      private void fixDown(int k) {
577          int j;
578          if (comparator == null) {
579 <            while ((j = k << 1) <= size && j > 0) {
580 <                if (j<size && ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
579 >            while ((j = k << 1) <= size && (j > 0)) {
580 >                if (j<size &&
581 >                    ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
582                      j++; // j indexes smallest kid
583 +
584                  if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
585                      break;
586                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
587                  k = j;
588              }
589          } else {
590 <            while ((j = k << 1) <= size && j > 0) {
591 <                if (j < size && comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
590 >            while ((j = k << 1) <= size && (j > 0)) {
591 >                if (j<size &&
592 >                    comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
593                      j++; // j indexes smallest kid
594                  if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
595                      break;
# Line 537 | Line 599 | public class PriorityQueue<E> extends Ab
599          }
600      }
601  
602 +    /**
603 +     * Establishes the heap invariant (described above) in the entire tree,
604 +     * assuming nothing about the order of the elements prior to the call.
605 +     */
606 +    private void heapify() {
607 +        for (int i = size/2; i >= 1; i--)
608 +            fixDown(i);
609 +    }
610  
611      /**
612       * Returns the comparator used to order this collection, or <tt>null</tt>
# Line 568 | Line 638 | public class PriorityQueue<E> extends Ab
638          s.writeInt(queue.length);
639  
640          // Write out all elements in the proper order.
641 <        for (int i=0; i<size; i++)
641 >        for (int i=1; i<=size; i++)
642              s.writeObject(queue[i]);
643      }
644  
# Line 587 | Line 657 | public class PriorityQueue<E> extends Ab
657          queue = new Object[arrayLength];
658  
659          // Read in all elements in the proper order.
660 <        for (int i=0; i<size; i++)
661 <            queue[i] = s.readObject();
660 >        for (int i=1; i<=size; i++)
661 >            queue[i] = (E) s.readObject();
662      }
663  
664   }
595

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines