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.11 by dholmes, Mon Jul 28 04:11:54 2003 UTC vs.
Revision 1.47 by dl, Sat Apr 10 14:31:46 2004 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 queue based on a priority heap.  This queue orders
12 < * elements according to an order specified at construction time, which is
13 < * specified in the same manner as {@link TreeSet} and {@link TreeMap}:
14 < * elements are ordered
15 < * either according to their <i>natural order</i> (see {@link Comparable}), or
16 < * according to a {@link Comparator}, depending on which constructor is used.
17 < * The <em>head</em> of this queue is the least element with respect to the
18 < * specified ordering. If multiple elements are tied for least value, the
19 < * head is one of those elements. A priority queue does not permit
13 < * <tt>null</tt> elements.
14 < *
15 < * <p>The {@link #remove()} and {@link #poll()} methods remove and
16 < * 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 may result
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.  It is always at least as large as the queue size.  As
31 < * elements are added to a priority queue, its capacity grows
32 < * 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>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> <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 35 | 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>, Sorted, java.io.Serializable {
65 >    implements java.io.Serializable {
66 >
67 >    private static final long serialVersionUID = -7720805057305804111L;
68  
69      private static final int DEFAULT_INITIAL_CAPACITY = 11;
70  
# Line 55 | Line 81 | public class PriorityQueue<E> extends Ab
81       *
82       * queue.length must be >= 2, even if size == 0.
83       */
84 <    private transient E[] queue;
84 >    private transient Object[] queue;
85  
86      /**
87       * The number of elements in the priority queue.
# Line 66 | Line 92 | public class PriorityQueue<E> extends Ab
92       * The comparator, or null if priority queue uses elements'
93       * natural ordering.
94       */
95 <    private final Comparator<E> comparator;
95 >    private final Comparator<? super E> comparator;
96  
97      /**
98       * The number of times this priority queue has been
# Line 75 | Line 101 | public class PriorityQueue<E> extends Ab
101      private transient int modCount = 0;
102  
103      /**
104 <     * Create a <tt>PriorityQueue</tt> with the default initial capacity
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);
110      }
111  
112      /**
113 <     * Create a <tt>PriorityQueue</tt> with the specified initial capacity
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
119 +     * than 1
120       */
121      public PriorityQueue(int initialCapacity) {
122          this(initialCapacity, null);
123      }
124  
125      /**
126 <     * Create a <tt>PriorityQueue</tt> with the specified initial capacity
126 >     * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
127       * that orders its elements according to the specified comparator.
128       *
129       * @param initialCapacity the initial capacity for this priority queue.
130       * @param comparator the comparator used to order this priority queue.
131       * If <tt>null</tt> then the order depends on the elements' natural
132       * ordering.
133 +     * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
134 +     * than 1
135       */
136 <    public PriorityQueue(int initialCapacity, Comparator<E> comparator) {
136 >    public PriorityQueue(int initialCapacity,
137 >                         Comparator<? super E> comparator) {
138          if (initialCapacity < 1)
139 <            initialCapacity = 1;
140 <        queue = (E[]) new Object[initialCapacity + 1];
139 >            throw new IllegalArgumentException();
140 >        this.queue = new Object[initialCapacity + 1];
141          this.comparator = comparator;
142      }
143  
144      /**
145 <     * Create a <tt>PriorityQueue</tt> containing the elements in the specified
146 <     * collection.  The priority queue has an initial capacity of 110% of the
116 <     * size of the specified collection. If the specified collection
117 <     * implements the {@link Sorted} interface, the priority queue will be
118 <     * sorted according to the same comparator, or according to its elements'
119 <     * natural order if the collection is sorted according to its elements'
120 <     * natural order.  If the specified collection does not implement
121 <     * <tt>Sorted</tt>, the priority queue is ordered according to
122 <     * its elements' natural order.
123 <     *
124 <     * @param initialElements the collection whose elements are to be placed
125 <     *        into this priority queue.
126 <     * @throws ClassCastException if elements of the specified collection
127 <     *         cannot be compared to one another according to the priority
128 <     *         queue's ordering.
129 <     * @throws NullPointerException if the specified collection or an
130 <     *         element of the specified collection is <tt>null</tt>.
145 >     * Common code to initialize underlying queue array across
146 >     * constructors below.
147       */
148 <    public PriorityQueue(Collection<E> initialElements) {
149 <        int sz = initialElements.size();
148 >    private void initializeArray(Collection<? extends E> c) {
149 >        int sz = c.size();
150          int initialCapacity = (int)Math.min((sz * 110L) / 100,
151                                              Integer.MAX_VALUE - 1);
152          if (initialCapacity < 1)
153              initialCapacity = 1;
138        queue = (E[]) new Object[initialCapacity + 1];
154  
155 <        if (initialElements instanceof Sorted) {
156 <            comparator = ((Sorted)initialElements).comparator();
157 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
158 <                queue[++size] = i.next();
155 >        this.queue = new Object[initialCapacity + 1];
156 >    }
157 >
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 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 >
168 >    /**
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 >            queue[++size] = i.next();
176 >        heapify();
177 >    }
178 >
179 >    /**
180 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
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 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
188 >     * elements' natural order.  Otherwise, the priority queue is
189 >     * ordered according to its elements' natural order.
190 >     *
191 >     * @param c the collection whose elements are to be placed
192 >     *        into this priority queue.
193 >     * @throws ClassCastException if elements of the specified collection
194 >     *         cannot be compared to one another according to the priority
195 >     *         queue's ordering.
196 >     * @throws NullPointerException if <tt>c</tt> or any element within it
197 >     * is <tt>null</tt>
198 >     */
199 >    public PriorityQueue(Collection<? extends E> c) {
200 >        initializeArray(c);
201 >        if (c instanceof SortedSet) {
202 >            SortedSet<? extends E> s = (SortedSet<? extends E>)c;
203 >            comparator = (Comparator<? super E>)s.comparator();
204 >            fillFromSorted(s);
205 >        } else if (c instanceof PriorityQueue) {
206 >            PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c;
207 >            comparator = (Comparator<? super E>)s.comparator();
208 >            fillFromSorted(s);
209          } else {
210              comparator = null;
211 <            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
147 <                add(i.next());
211 >            fillFromUnsorted(c);
212          }
213      }
214  
215 <    // Queue Methods
215 >    /**
216 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
217 >     * specified collection.  The priority queue has an initial
218 >     * capacity of 110% of the size of the specified collection or 1
219 >     * if the collection is empty.  This priority queue will be sorted
220 >     * according to the same comparator as the given collection, or
221 >     * according to its elements' natural order if the collection is
222 >     * sorted according to its elements' natural order.
223 >     *
224 >     * @param c the collection whose elements are to be placed
225 >     *        into this priority queue.
226 >     * @throws ClassCastException if elements of the specified collection
227 >     *         cannot be compared to one another according to the priority
228 >     *         queue's ordering.
229 >     * @throws NullPointerException if <tt>c</tt> or any element within it
230 >     * is <tt>null</tt>
231 >     */
232 >    public PriorityQueue(PriorityQueue<? extends E> c) {
233 >        initializeArray(c);
234 >        comparator = (Comparator<? super E>)c.comparator();
235 >        fillFromSorted(c);
236 >    }
237  
238      /**
239 <     * Add the specified element to this priority queue.
239 >     * Creates a <tt>PriorityQueue</tt> containing the elements in the
240 >     * specified collection.  The priority queue has an initial
241 >     * capacity of 110% of the size of the specified collection or 1
242 >     * if the collection is empty.  This priority queue will be sorted
243 >     * according to the same comparator as the given collection, or
244 >     * according to its elements' natural order if the collection is
245 >     * sorted according to its elements' natural order.
246 >     *
247 >     * @param c the collection whose elements are to be placed
248 >     *        into this priority queue.
249 >     * @throws ClassCastException if elements of the specified collection
250 >     *         cannot be compared to one another according to the priority
251 >     *         queue's ordering.
252 >     * @throws NullPointerException if <tt>c</tt> or any element within it
253 >     * is <tt>null</tt>
254 >     */
255 >    public PriorityQueue(SortedSet<? extends E> c) {
256 >        initializeArray(c);
257 >        comparator = (Comparator<? super E>)c.comparator();
258 >        fillFromSorted(c);
259 >    }
260 >
261 >    /**
262 >     * Resize array, if necessary, to be able to hold given index
263 >     */
264 >    private void grow(int index) {
265 >        int newlen = queue.length;
266 >        if (index < newlen) // don't need to grow
267 >            return;
268 >        if (index == Integer.MAX_VALUE)
269 >            throw new OutOfMemoryError();
270 >        while (newlen <= index) {
271 >            if (newlen >= Integer.MAX_VALUE / 2)  // avoid overflow
272 >                newlen = Integer.MAX_VALUE;
273 >            else
274 >                newlen <<= 2;
275 >        }
276 >        Object[] newQueue = new Object[newlen];
277 >        System.arraycopy(queue, 0, newQueue, 0, queue.length);
278 >        queue = newQueue;
279 >    }
280 >            
281 >
282 >    /**
283 >     * Inserts the specified element into this priority queue.
284       *
156     * @param element the element to add.
285       * @return <tt>true</tt>
286       * @throws ClassCastException if the specified element cannot be compared
287       * with elements currently in the priority queue according
288       * to the priority queue's ordering.
289 <     * @throws NullPointerException if the specified element is null.
289 >     * @throws NullPointerException if the specified element is <tt>null</tt>.
290       */
291 <    public boolean offer(E element) {
292 <        if (element == null)
291 >    public boolean offer(E o) {
292 >        if (o == null)
293              throw new NullPointerException();
294          modCount++;
295          ++size;
296  
297          // Grow backing store if necessary
298 <        while (size >= queue.length) {
299 <            E[] newQueue = (E[]) new Object[2 * queue.length];
172 <            System.arraycopy(queue, 0, newQueue, 0, queue.length);
173 <            queue = newQueue;
174 <        }
298 >        if (size >= queue.length)
299 >            grow(size);
300  
301 <        queue[size] = element;
301 >        queue[size] = o;
302          fixUp(size);
303          return true;
304      }
305  
306 <    public E poll() {
306 >    public E peek() {
307          if (size == 0)
308              return null;
309 <        return remove(1);
185 <    }
186 <
187 <    public E peek() {
188 <        return queue[1];
309 >        return (E) queue[1];
310      }
311  
312 <    // Collection Methods
192 <
193 <    // these first two override just to get the throws docs
312 >    // Collection Methods - the first two override to update docs
313  
314      /**
315 +     * Adds the specified element to this queue.
316 +     * @return <tt>true</tt> (as per the general contract of
317 +     * <tt>Collection.add</tt>).
318 +     *
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 element) {
325 <        return super.add(element);
200 <    }
201 <
202 <    /**
203 <     * @throws NullPointerException if any element is <tt>null</tt>.
204 <     */
205 <    public boolean addAll(Collection c) {
206 <        return super.addAll(c);
324 >    public boolean add(E o) {
325 >        return offer(o);
326      }
327  
328 <    /**
210 <     * @throws NullPointerException if the specified element is <tt>null</tt>.
211 <     */
212 <    public boolean remove(E o) {
328 >    public boolean remove(Object o) {
329          if (o == null)
330 <            throw new NullPointerException();
330 >            return false;
331  
332          if (comparator == null) {
333              for (int i = 1; i <= size; i++) {
334 <                if (((Comparable)queue[i]).compareTo(o) == 0) {
335 <                    remove(i);
334 >                if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
335 >                    removeAt(i);
336                      return true;
337                  }
338              }
339          } else {
340              for (int i = 1; i <= size; i++) {
341 <                if (comparator.compare(queue[i], o) == 0) {
342 <                    remove(i);
341 >                if (comparator.compare((E)queue[i], (E)o) == 0) {
342 >                    removeAt(i);
343                      return true;
344                  }
345              }
# Line 232 | Line 348 | public class PriorityQueue<E> extends Ab
348      }
349  
350      /**
351 <     * Returns an iterator over the elements in this priority queue.  The
352 <     * elements of the priority queue will be returned by this iterator in the
237 <     * order specified by the queue, which is to say the order they would be
238 <     * returned by repeated calls to <tt>poll</tt>.
351 >     * Returns an iterator over the elements in this queue. The iterator
352 >     * does not return the elements in any particular order.
353       *
354 <     * @return an <tt>Iterator</tt> over the elements in this priority queue.
354 >     * @return an iterator over the elements in this queue.
355       */
356      public Iterator<E> iterator() {
357          return new Itr();
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 251 | 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 264 | 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 = 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() {
281            if (lastRet == 0)
282                throw new IllegalStateException();
426              checkForComodification();
427  
428 <            PriorityQueue.this.remove(lastRet);
429 <            if (lastRet < cursor)
430 <                cursor--;
431 <            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 295 | Line 451 | public class PriorityQueue<E> extends Ab
451          }
452      }
453  
298    /**
299     * Returns the number of elements in this priority queue.
300     *
301     * @return the number of elements in this priority queue.
302     */
454      public int size() {
455          return size;
456      }
# Line 317 | 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 <     * XXX: Could further special-case i==size, but is it worth it?
490 <     * XXX: Could special-case i==0, but is it worth it?
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 = 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 349 | Line 526 | public class PriorityQueue<E> extends Ab
526          if (comparator == null) {
527              while (k > 1) {
528                  int j = k >> 1;
529 <                if (((Comparable)queue[j]).compareTo(queue[k]) <= 0)
529 >                if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 0)
530                      break;
531 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
531 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
532                  k = j;
533              }
534          } else {
535              while (k > 1) {
536 <                int j = k >> 1;
537 <                if (comparator.compare(queue[j], queue[k]) <= 0)
536 >                int j = k >>> 1;
537 >                if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
538                      break;
539 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
539 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
540                  k = j;
541              }
542          }
# Line 377 | Line 554 | public class PriorityQueue<E> extends Ab
554      private void fixDown(int k) {
555          int j;
556          if (comparator == null) {
557 <            while ((j = k << 1) <= size) {
558 <                if (j<size && ((Comparable)queue[j]).compareTo(queue[j+1]) > 0)
557 >            while ((j = k << 1) <= size && (j > 0)) {
558 >                if (j<size &&
559 >                    ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
560                      j++; // j indexes smallest kid
561 <                if (((Comparable)queue[k]).compareTo(queue[j]) <= 0)
561 >
562 >                if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
563                      break;
564 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
564 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
565                  k = j;
566              }
567          } else {
568 <            while ((j = k << 1) <= size) {
569 <                if (j < size && comparator.compare(queue[j], queue[j+1]) > 0)
568 >            while ((j = k << 1) <= size && (j > 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(queue[k], queue[j]) <= 0)
572 >                if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
573                      break;
574 <                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
574 >                Object tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
575                  k = j;
576              }
577          }
578      }
579  
580 <    public Comparator comparator() {
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>
591 >     * if this collection is sorted according to its elements natural ordering
592 >     * (using <tt>Comparable</tt>).
593 >     *
594 >     * @return the comparator used to order this collection, or <tt>null</tt>
595 >     * if this collection is sorted according to its elements natural ordering.
596 >     */
597 >    public Comparator<? super E> comparator() {
598          return comparator;
599      }
600  
# Line 410 | Line 607 | public class PriorityQueue<E> extends Ab
607       * <tt>Object</tt>) in the proper order.
608       * @param s the stream
609       */
610 <    private synchronized void writeObject(java.io.ObjectOutputStream s)
610 >    private void writeObject(java.io.ObjectOutputStream s)
611          throws java.io.IOException{
612          // Write out element count, and any hidden stuff
613          s.defaultWriteObject();
# Line 419 | 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 428 | Line 625 | public class PriorityQueue<E> extends Ab
625       * deserialize it).
626       * @param s the stream
627       */
628 <    private synchronized void readObject(java.io.ObjectInputStream s)
628 >    private void readObject(java.io.ObjectInputStream s)
629          throws java.io.IOException, ClassNotFoundException {
630          // Read in size, and any hidden stuff
631          s.defaultReadObject();
632  
633          // Read in array length and allocate array
634          int arrayLength = s.readInt();
635 <        queue = (E[]) new Object[arrayLength];
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] = (E)s.readObject();
638 >        for (int i=1; i<=size; i++)
639 >            queue[i] = (E) s.readObject();
640      }
641  
642   }
446

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines