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.33 by dl, Mon Aug 25 23:50:24 2003 UTC vs.
Revision 1.42 by dl, Mon Sep 15 12:02:23 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
13 < * respect to the specified ordering.
14 < * If multiple elements are tied for least value, the
15 < * head is one of those elements. A priority queue does not permit
16 < * <tt>null</tt> elements.
17 < *
18 < * <p>The {@link #remove()} and {@link #poll()} methods remove and
19 < * return the head of the queue.
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 results
19 > * in <tt>ClassCastException</tt>).
20   *
21 < * <p>The {@link #element()} and {@link #peek()} methods return, but do
22 < * not delete, the head of the queue.
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>A priority queue has a <i>capacity</i>.  The capacity is the
29 < * size of the array used internally to store the elements on the
30 < * queue.
31 < * It is always at least as large as the queue size.  As
32 < * elements are added to a priority queue, its capacity grows
33 < * automatically.  The details of the growth policy are not specified.
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 Iterator provided in method {@link #iterator()} is <em>not</em>
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>.
# Line 37 | Line 43
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.BlockingPriorityQueue} class.
46 > * java.util.concurrent.PriorityBlockingQueue} class.
47   *
48   *
49   * <p>Implementation note: this implementation provides O(log(n)) time
# Line 51 | 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   */
63   public class PriorityQueue<E> extends AbstractQueue<E>
# Line 150 | Line 157 | public class PriorityQueue<E> extends Ab
157      /**
158       * Initially fill elements of the queue array under the
159       * knowledge that it is sorted or is another PQ, in which
160 <     * case we can just place the elements without fixups.
160 >     * case we can just place the elements in the order presented.
161       */
162      private void fillFromSorted(Collection<? extends E> c) {
163          for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
164              queue[++size] = i.next();
165      }
166  
160
167      /**
168 <     * Initially fill elements of the queue array that is
169 <     * not to our knowledge sorted, so we must add them
170 <     * one by one.
168 >     * Initially fill elements of the queue array that is not to our knowledge
169 >     * sorted, so we must rearrange the elements to guarantee the heap
170 >     * invariant.
171       */
172      private void fillFromUnsorted(Collection<? extends E> c) {
173          for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
174 <            add(i.next());
174 >            queue[++size] = i.next();
175 >        heapify();
176      }
177  
178      /**
# Line 271 | Line 278 | public class PriorityQueue<E> extends Ab
278          queue = newQueue;
279      }
280              
274    // Queue Methods
275
276
281  
282      /**
283 <     * Add the specified element to this priority queue.
283 >     * Inserts the specified element into this priority queue.
284       *
285       * @return <tt>true</tt>
286       * @throws ClassCastException if the specified element cannot be compared
# Line 299 | Line 303 | public class PriorityQueue<E> extends Ab
303          return true;
304      }
305  
306 <    public E poll() {
306 >    public E peek() {
307          if (size == 0)
308              return null;
305        return (E) remove(1);
306    }
307
308    public E peek() {
309          return (E) queue[1];
310      }
311  
# Line 316 | Line 316 | public class PriorityQueue<E> extends Ab
316       * @return <tt>true</tt> (as per the general contract of
317       * <tt>Collection.add</tt>).
318       *
319 <     * @throws NullPointerException {@inheritDoc}
319 >     * @throws NullPointerException if the specified element is <tt>null</tt>.
320       * @throws ClassCastException if the specified element cannot be compared
321       * with elements currently in the priority queue according
322       * to the priority queue's ordering.
323       */
324      public boolean add(E o) {
325 <        return super.add(o);
326 <    }
327 <
328 <  
329 <    /**
330 <     * Adds all of the elements in the specified collection to this queue.
331 <     * The behavior of this operation is undefined if
332 <     * the specified collection is modified while the operation is in
333 <     * progress.  (This implies that the behavior of this call is undefined if
334 <     * the specified collection is this queue, and this queue is nonempty.)
335 <     * <p>
336 <     * This implementation iterates over the specified collection, and adds
337 <     * each object returned by the iterator to this collection, in turn.
338 <     * @throws NullPointerException {@inheritDoc}
339 <     * @throws ClassCastException if any element cannot be compared
340 <     * with elements currently in the priority queue according
341 <     * to the priority queue's ordering.
342 <     */
343 <    public boolean addAll(Collection<? extends E> c) {
344 <        return super.addAll(c);
325 >        return offer(o);
326      }
327  
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     */
328      public boolean remove(Object o) {
329          if (o == null)
330              return false;
# Line 366 | Line 332 | public class PriorityQueue<E> extends Ab
332          if (comparator == null) {
333              for (int i = 1; i <= size; i++) {
334                  if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
335 <                    remove(i);
335 >                    removeAt(i);
336                      return true;
337                  }
338              }
339          } else {
340              for (int i = 1; i <= size; i++) {
341                  if (comparator.compare((E)queue[i], (E)o) == 0) {
342 <                    remove(i);
342 >                    removeAt(i);
343                      return true;
344                  }
345              }
# Line 392 | Line 358 | public class PriorityQueue<E> extends Ab
358      }
359  
360      private class Itr implements Iterator<E> {
361 +
362          /**
363           * Index (into queue array) of element to be returned by
364           * subsequent call to next.
# Line 399 | Line 366 | public class PriorityQueue<E> extends Ab
366          private int cursor = 1;
367  
368          /**
369 <         * Index of element returned by most recent call to next or
370 <         * previous.  Reset to 0 if this element is deleted by a call
371 <         * to remove.
369 >         * Index of element returned by most recent call to next,
370 >         * unless that element came from the forgetMeNot list.
371 >         * Reset to 0 if element is deleted by a call to remove.
372           */
373          private int lastRet = 0;
374  
# Line 412 | Line 379 | public class PriorityQueue<E> extends Ab
379           */
380          private int expectedModCount = modCount;
381  
382 +        /**
383 +         * A list of elements that were moved from the unvisited portion of
384 +         * the heap into the visited portion as a result of "unlucky" element
385 +         * removals during the iteration.  (Unlucky element removals are those
386 +         * that require a fixup instead of a fixdown.)  We must visit all of
387 +         * the elements in this list to complete the iteration.  We do this
388 +         * after we've completed the "normal" iteration.
389 +         *
390 +         * We expect that most iterations, even those involving removals,
391 +         * will not use need to store elements in this field.
392 +         */
393 +        private ArrayList<E> forgetMeNot = null;
394 +
395 +        /**
396 +         * Element returned by the most recent call to next iff that
397 +         * element was drawn from the forgetMeNot list.
398 +         */
399 +        private Object lastRetElt = null;
400 +
401          public boolean hasNext() {
402 <            return cursor <= size;
402 >            return cursor <= size || forgetMeNot != null;
403          }
404  
405          public E next() {
406              checkForComodification();
407 <            if (cursor > size)
407 >            E result;
408 >            if (cursor <= size) {
409 >                result = (E) queue[cursor];
410 >                lastRet = cursor++;
411 >            }
412 >            else if (forgetMeNot == null)
413                  throw new NoSuchElementException();
414 <            E result = (E) queue[cursor];
415 <            lastRet = cursor++;
414 >            else {
415 >                int remaining = forgetMeNot.size();
416 >                result = forgetMeNot.remove(remaining - 1);
417 >                if (remaining == 1)
418 >                    forgetMeNot = null;
419 >                lastRet = 0;
420 >                lastRetElt = result;
421 >            }
422              return result;
423          }
424  
425          public void remove() {
429            if (lastRet == 0)
430                throw new IllegalStateException();
426              checkForComodification();
427  
428 <            PriorityQueue.this.remove(lastRet);
429 <            cursor--;
430 <            lastRet = 0;
428 >            if (lastRet != 0) {
429 >                E moved = PriorityQueue.this.removeAt(lastRet);
430 >                lastRet = 0;
431 >                if (moved == null) {
432 >                    cursor--;
433 >                } else {
434 >                    if (forgetMeNot == null)
435 >                        forgetMeNot = new ArrayList<E>();
436 >                    forgetMeNot.add(moved);
437 >                }
438 >            } else if (lastRetElt != null) {
439 >                PriorityQueue.this.remove(lastRetElt);
440 >                lastRetElt = null;
441 >            } else {
442 >                throw new IllegalStateException();
443 >            }
444 >
445              expectedModCount = modCount;
446          }
447  
# Line 459 | Line 468 | public class PriorityQueue<E> extends Ab
468          size = 0;
469      }
470  
471 +    public E poll() {
472 +        if (size == 0)
473 +            return null;
474 +        modCount++;
475 +
476 +        E result = (E) queue[1];
477 +        queue[1] = queue[size];
478 +        queue[size--] = null;  // Drop extra ref to prevent memory leak
479 +        if (size > 1)
480 +            fixDown(1);
481 +
482 +        return result;
483 +    }
484 +
485      /**
486 <     * Removes and returns the ith element from queue.  Recall
487 <     * that queue is one-based, so 1 <= i <= size.
486 >     * Removes and returns the ith element from queue.  (Recall that queue
487 >     * is one-based, so 1 <= i <= size.)
488       *
489 +     * Normally this method leaves the elements at positions from 1 up to i-1,
490 +     * inclusive, untouched.  Under these circumstances, it returns null.
491 +     * Occasionally, in order to maintain the heap invariant, it must move
492 +     * the last element of the list to some index in the range [2, i-1],
493 +     * and move the element previously at position (i/2) to position i.
494 +     * Under these circumstances, this method returns the element that was
495 +     * previously at the end of the list and is now at some position between
496 +     * 2 and i-1 inclusive.
497       */
498 <    private E remove(int i) {
499 <        assert i <= size;
498 >    private E removeAt(int i) {
499 >        assert i > 0 && i <= size;
500          modCount++;
501  
502 <        E result = (E) queue[i];
503 <        queue[i] = queue[size];
502 >        E moved = (E) queue[size];
503 >        queue[i] = moved;
504          queue[size--] = null;  // Drop extra ref to prevent memory leak
505 <        if (i <= size)
505 >        if (i <= size) {
506              fixDown(i);
507 <        return result;
507 >            if (queue[i] == moved) {
508 >                fixUp(i);
509 >                if (queue[i] != moved)
510 >                    return moved;
511 >            }
512 >        }
513 >        return null;
514      }
515  
516      /**
# Line 496 | Line 533 | public class PriorityQueue<E> extends Ab
533              }
534          } else {
535              while (k > 1) {
536 <                int j = k >> 1;
536 >                int j = k >>> 1;
537                  if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
538                      break;
539                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
# Line 518 | Line 555 | public class PriorityQueue<E> extends Ab
555          int j;
556          if (comparator == null) {
557              while ((j = k << 1) <= size && (j > 0)) {
558 <                if (j<size && ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
558 >                if (j<size &&
559 >                    ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
560                      j++; // j indexes smallest kid
561 +
562                  if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
563                      break;
564                  Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
# Line 527 | Line 566 | public class PriorityQueue<E> extends Ab
566              }
567          } else {
568              while ((j = k << 1) <= size && (j > 0)) {
569 <                if (j < size && comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
569 >                if (j<size &&
570 >                    comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
571                      j++; // j indexes smallest kid
572                  if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
573                      break;
# Line 537 | Line 577 | public class PriorityQueue<E> extends Ab
577          }
578      }
579  
580 +    /**
581 +     * Establishes the heap invariant (described above) in the entire tree,
582 +     * assuming nothing about the order of the elements prior to the call.
583 +     */
584 +    private void heapify() {
585 +        for (int i = size/2; i >= 1; i--)
586 +            fixDown(i);
587 +    }
588  
589      /**
590       * Returns the comparator used to order this collection, or <tt>null</tt>
# Line 568 | Line 616 | public class PriorityQueue<E> extends Ab
616          s.writeInt(queue.length);
617  
618          // Write out all elements in the proper order.
619 <        for (int i=0; i<size; i++)
619 >        for (int i=1; i<=size; i++)
620              s.writeObject(queue[i]);
621      }
622  
# Line 587 | Line 635 | public class PriorityQueue<E> extends Ab
635          queue = new Object[arrayLength];
636  
637          // Read in all elements in the proper order.
638 <        for (int i=0; i<size; i++)
639 <            queue[i] = s.readObject();
638 >        for (int i=1; i<=size; i++)
639 >            queue[i] = (E) s.readObject();
640      }
641  
642   }
595

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines