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.35 by dl, Wed Aug 27 10:27:07 2003 UTC vs.
Revision 1.38 by dl, Mon Sep 1 12:23:28 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
10 < * 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   * <p>The <em>head</em> of this queue is the <em>least</em> element with
18 < * respect to the specified ordering.
19 < * If multiple elements are tied for least value, the
15 < * head is one of those elements. A priority queue does not permit
18 > * respect to the specified ordering.  If multiple elements are tied for least
19 > * value, the head is one of those elements. A priority queue does not permit
20   * <tt>null</tt> elements.
21   *
22   * <p>The {@link #remove()} and {@link #poll()} methods remove and
# Line 51 | Line 55
55   * <a href="{@docRoot}/../guide/collections/index.html">
56   * Java Collections Framework</a>.
57   * @since 1.5
58 + * @version %I%, %G%
59   * @author Josh Bloch
60   */
61   public class PriorityQueue<E> extends AbstractQueue<E>
# Line 150 | Line 155 | public class PriorityQueue<E> extends Ab
155      /**
156       * Initially fill elements of the queue array under the
157       * knowledge that it is sorted or is another PQ, in which
158 <     * case we can just place the elements without fixups.
158 >     * case we can just place the elements in the order presented.
159       */
160      private void fillFromSorted(Collection<? extends E> c) {
161          for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
162              queue[++size] = i.next();
163      }
164  
160
165      /**
166 <     * Initially fill elements of the queue array that is
167 <     * not to our knowledge sorted, so we must add them
168 <     * one by one.
166 >     * Initially fill elements of the queue array that is not to our knowledge
167 >     * sorted, so we must rearrange the elements to guarantee the heap
168 >     * invariant.
169       */
170      private void fillFromUnsorted(Collection<? extends E> c) {
171          for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
172 <            add(i.next());
172 >            queue[++size] = i.next();
173 >        heapify();
174      }
175  
176      /**
# Line 271 | Line 276 | public class PriorityQueue<E> extends Ab
276          queue = newQueue;
277      }
278              
274    // Queue Methods
275
279  
280 +    // Queue Methods
281  
282      /**
283       * Add the specified element to this priority queue.
# Line 302 | Line 306 | public class PriorityQueue<E> extends Ab
306      public E poll() {
307          if (size == 0)
308              return null;
309 <        return (E) remove(1);
309 >        return remove();
310      }
311  
312      public E peek() {
# Line 345 | Line 349 | public class PriorityQueue<E> extends Ab
349      }
350  
351  
352 < /**
352 >    /**
353       * Removes a single instance of the specified element from this
354       * queue, if it is present.  More formally,
355       * removes an element <tt>e</tt> such that <tt>(o==null ? e==null :
# Line 366 | Line 370 | public class PriorityQueue<E> extends Ab
370          if (comparator == null) {
371              for (int i = 1; i <= size; i++) {
372                  if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
373 <                    remove(i);
373 >                    removeAt(i);
374                      return true;
375                  }
376              }
377          } else {
378              for (int i = 1; i <= size; i++) {
379                  if (comparator.compare((E)queue[i], (E)o) == 0) {
380 <                    remove(i);
380 >                    removeAt(i);
381                      return true;
382                  }
383              }
# Line 400 | Line 404 | public class PriorityQueue<E> extends Ab
404          private int cursor = 1;
405  
406          /**
407 <         * Index of element returned by most recent call to next or
408 <         * previous.  Reset to 0 if this element is deleted by a call
409 <         * to remove.
407 >         * Index of element returned by most recent call to next,
408 >         * unless that element came from the forgetMeNot list.
409 >         * Reset to 0 if element is deleted by a call to remove.
410           */
411          private int lastRet = 0;
412  
# Line 413 | Line 417 | public class PriorityQueue<E> extends Ab
417           */
418          private int expectedModCount = modCount;
419  
420 <        // Workarounds until version that better handles remove() installed.
421 <        // These are used to copy-on-write the array upon first remove
422 <        private Object[] q = queue;
423 <        private int qsize = size;
420 >        /**
421 >         * A list of elements that were moved from the unvisited portion of
422 >         * the heap into the visited portion as a result of "unlucky" element
423 >         * removals during the iteration.  (Unlucky element removals are those
424 >         * that require a fixup instead of a fixdown.)  We must visit all of
425 >         * the elements in this list to complete the iteration.  We do this
426 >         * after we've completed the "normal" iteration.
427 >         *
428 >         * We expect that most iterations, even those involving removals,
429 >         * will not use need to store elements in this field.
430 >         */
431 >        private ArrayList<E> forgetMeNot = null;
432 >
433 >        /**
434 >         * Element returned by the most recent call to next iff that
435 >         * element was drawn from the forgetMeNot list.
436 >         */
437 >        private Object lastRetElt = null;
438  
439          public boolean hasNext() {
440 <            return cursor <= qsize;
440 >            return cursor <= size || forgetMeNot != null;
441          }
442  
443          public E next() {
444              checkForComodification();
445 <            if (cursor > qsize)
445 >            E result;
446 >            if (cursor <= size) {
447 >                result = (E) queue[cursor];
448 >                lastRet = cursor++;
449 >            }
450 >            else if (forgetMeNot == null)
451                  throw new NoSuchElementException();
452 <            E result = (E) q[cursor];
453 <            lastRet = cursor++;
452 >            else {
453 >                int remaining = forgetMeNot.size();
454 >                result = forgetMeNot.remove(remaining - 1);
455 >                if (remaining == 1)
456 >                    forgetMeNot = null;
457 >                lastRet = 0;
458 >                lastRetElt = result;
459 >            }
460              return result;
461          }
462  
463          public void remove() {
435            if (lastRet == 0)
436                throw new IllegalStateException();
464              checkForComodification();
465  
466 <            // Copy on first remove
467 <            if (q == queue) {
468 <                q = new Object[queue.length];
469 <                System.arraycopy(queue, 0, q, 0, queue.length);
466 >            if (lastRet != 0) {
467 >                E moved = PriorityQueue.this.removeAt(lastRet);
468 >                lastRet = 0;
469 >                if (moved == null) {
470 >                    cursor--;
471 >                } else {
472 >                    if (forgetMeNot == null)
473 >                        forgetMeNot = new ArrayList<E>();
474 >                    forgetMeNot.add(moved);
475 >                }
476 >            } else if (lastRetElt != null) {
477 >                PriorityQueue.this.remove(lastRetElt);
478 >                lastRetElt = null;
479 >            } else {
480 >                throw new IllegalStateException();
481              }
444            PriorityQueue.this.remove(q[lastRet]);
482  
446            lastRet = 0;
483              expectedModCount = modCount;
484          }
485  
# Line 471 | Line 507 | public class PriorityQueue<E> extends Ab
507      }
508  
509      /**
510 <     * Removes and returns the ith element from queue.  Recall
511 <     * that queue is one-based, so 1 <= i <= size.
510 >     * Removes and returns the first element from queue.
511 >     */
512 >    public E remove() {
513 >        if (size == 0)
514 >            throw new NoSuchElementException();
515 >        modCount++;
516 >
517 >        E result = (E) queue[1];
518 >        queue[1] = queue[size];
519 >        queue[size--] = null;  // Drop extra ref to prevent memory leak
520 >        if (size > 1)
521 >            fixDown(1);
522 >
523 >        return result;
524 >    }
525 >
526 >    /**
527 >     * Removes and returns the ith element from queue.  (Recall that queue
528 >     * is one-based, so 1 <= i <= size.)
529       *
530 +     * Normally this method leaves the elements at positions from 1 up to i-1,
531 +     * inclusive, untouched.  Under these circumstances, it returns null.
532 +     * Occasionally, in order to maintain the heap invariant, it must move
533 +     * the last element of the list to some index in the range [2, i-1],
534 +     * and move the element previously at position (i/2) to position i.
535 +     * Under these circumstances, this method returns the element that was
536 +     * previously at the end of the list and is now at some position between
537 +     * 2 and i-1 inclusive.
538       */
539 <    private E remove(int i) {
540 <        assert i <= size;
539 >    private E removeAt(int i) {
540 >        assert i > 0 && i <= size;
541          modCount++;
542  
543 <        E result = (E) queue[i];
544 <        queue[i] = queue[size];
543 >        E moved = (E) queue[size];
544 >        queue[i] = moved;
545          queue[size--] = null;  // Drop extra ref to prevent memory leak
546          if (i <= size) {
547              fixDown(i);
548 <            fixUp(i);
548 >            if (queue[i] == moved) {
549 >                fixUp(i);
550 >                if (queue[i] != moved)
551 >                    return moved;
552 >            }
553          }
554 <
490 <        return result;
554 >        return null;
555      }
556  
557      /**
# Line 552 | Line 616 | public class PriorityQueue<E> extends Ab
616                  k = j;
617              }
618          }
555
619      }
620  
621 +    /**
622 +     * Establishes the heap invariant (described above) in the entire tree,
623 +     * assuming nothing about the order of the elements prior to the call.
624 +     */
625 +    private void heapify() {
626 +        for (int i = size/2; i >= 1; i--)
627 +            fixDown(i);
628 +    }
629  
630      /**
631       * Returns the comparator used to order this collection, or <tt>null</tt>
# Line 606 | Line 677 | public class PriorityQueue<E> extends Ab
677  
678          // Read in all elements in the proper order.
679          for (int i=0; i<size; i++)
680 <            queue[i] = s.readObject();
680 >            queue[i] = (E) s.readObject();
681      }
682  
683   }
613

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines