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.1 by tim, Wed May 14 21:30:45 2003 UTC vs.
Revision 1.2 by tim, Sun May 18 18:10:02 2003 UTC

# Line 1 | Line 1
1 < package java.util;
1 > package java.util;
2  
3 < import java.util.*;
3 > /*
4 > * Todo
5 > *
6 > *   1) Make it serializable.
7 > */
8  
9   /**
10 < * An unbounded (resizable) priority queue based on a priority
11 < * heap.The take operation returns the least element with respect to
12 < * the given ordering. (If more than one element is tied for least
13 < * value, one of them is arbitrarily chosen to be returned -- no
14 < * guarantees are made for ordering across ties.) Ordering follows the
15 < * java.util.Collection conventions: Either the elements must be
16 < * Comparable, or a Comparator must be supplied. Comparison failures
17 < * throw ClassCastExceptions during insertions and extractions.
18 < **/
19 < public class PriorityQueue<E> extends AbstractCollection<E> implements Queue<E> {
20 <    public PriorityQueue(int initialCapacity) {}
21 <    public PriorityQueue(int initialCapacity, Comparator comparator) {}
10 > * An unbounded priority queue based on a priority heap.  This queue orders
11 > * elements according to the order specified at creation time.  This order is
12 > * specified as for {@link TreeSet} and {@link TreeMap}: Elements are ordered
13 > * either according to their <i>natural order</i> (see {@link Comparable}), or
14 > * according to a {@link Comparator}, depending on which constructor is used.
15 > * The {@link #peek}, {@link #poll}, and {@link #remove} methods return the
16 > * minimal element with respect to the specified ordering.  If multiple
17 > * these elements are tied for least value, no guarantees are made as to
18 > * which of elements is returned.
19 > *
20 > * <p>Each priority queue has a <i>capacity</i>.  The capacity is the size of
21 > * the array used to store the elements on the queue.  It is always at least
22 > * as large as the queue size.  As elements are added to a priority list,
23 > * its capacity grows automatically.  The details of the growth policy are not
24 > * specified.
25 > *
26 > *<p>Implementation note: this implementation provides O(log(n)) time for
27 > * the <tt>offer</tt>, <tt>poll</tt>, <tt>remove()</tt> and <tt>add</tt>
28 > * methods; linear time for the <tt>remove(Object)</tt> and
29 > * <tt>contains</tt> methods; and constant time for the <tt>peek</tt>,
30 > * <tt>element</tt>, and <tt>size</tt> methods.
31 > *
32 > * <p>This class is a member of the
33 > * <a href="{@docRoot}/../guide/collections/index.html">
34 > * Java Collections Framework</a>.
35 > */
36 > public class PriorityQueue<E> extends AbstractQueue<E>
37 >                              implements Queue<E>
38 > {
39 >    private static final int DEFAULT_INITIAL_CAPACITY = 11;
40  
41 <    public PriorityQueue(int initialCapacity, Collection initialElements) {}
41 >    /**
42 >     * Priority queue represented as a balanced binary heap: the two children
43 >     * of queue[n] are queue[2*n] and queue[2*n + 1].  The priority queue is
44 >     * ordered by comparator, or by the elements' natural ordering, if
45 >     * comparator is null:  For each node n in the heap, and each descendant
46 >     * of n, d, n <= d.
47 >     *
48 >     * The element with the lowest value is in queue[1] (assuming the queue is
49 >     * nonempty). A one-based array is used in preference to the traditional
50 >     * zero-based array to simplify parent and child calculations.
51 >     *
52 >     * queue.length must be >= 2, even if size == 0.
53 >     */
54 >    private E[] queue;
55  
56 <    public PriorityQueue(int initialCapacity, Comparator comparator, Collection initialElements) {}
56 >    /**
57 >     * The number of elements in the priority queue.
58 >     */
59 >    private int size = 0;
60  
61 <    public boolean add(E x) {
62 <        return false;
63 <    }
64 <    public boolean offer(E x) {
65 <        return false;
66 <    }
67 <    public boolean remove(Object x) {
68 <        return false;
61 >    /**
62 >     * The comparator, or null if priority queue uses elements'
63 >     * natural ordering.
64 >     */
65 >    private final Comparator<E> comparator;
66 >
67 >    /**
68 >     * The number of times this priority queue has been
69 >     * <i>structurally modified</i>.  See AbstractList for gory details.
70 >     */
71 >    private int modCount = 0;
72 >
73 >    /**
74 >     * Create a new priority queue with the default initial capacity (11)
75 >     * that orders its elements according to their natural ordering.
76 >     */
77 >    public PriorityQueue() {
78 >        this(DEFAULT_INITIAL_CAPACITY);
79      }
80  
81 <    public E remove() {
82 <        return null;
81 >    /**
82 >     * Create a new priority queue with the specified initial capacity
83 >     * that orders its elements according to their natural ordering.
84 >     *
85 >     * @param initialCapacity the initial capacity for this priority queue.
86 >     */
87 >    public PriorityQueue(int initialCapacity) {
88 >        this(initialCapacity, null);
89      }
90 <    public Iterator<E> iterator() {
91 <      return null;
90 >
91 >    /**
92 >     * Create a new priority queue with the specified initial capacity (11)
93 >     * that orders its elements according to the specified comparator.
94 >     *
95 >     * @param initialCapacity the initial capacity for this priority queue.
96 >     * @param comparator the comparator used to order this priority queue.
97 >     */
98 >    public PriorityQueue(int initialCapacity, Comparator<E> comparator) {
99 >        if (initialCapacity < 1)
100 >            initialCapacity = 1;
101 >        queue = new E[initialCapacity + 1];
102 >        this.comparator = comparator;
103      }
104  
105 <    public E element() {
106 <        return null;
105 >    /**
106 >     * Create a new priority queue containing the elements in the specified
107 >     * collection.  The priority queue has an initial capacity of 110% of the
108 >     * size of the specified collection. If the specified collection
109 >     * implements the {@link Sorted} interface, the priority queue will be
110 >     * sorted according to the same comparator, or according to its elements'
111 >     * natural order if the collection is sorted according to its elements'
112 >     * natural order.  If the specified collection does not implement the
113 >     * <tt>Sorted</tt> interface, the priority queue is ordered according to
114 >     * its elements' natural order.
115 >     *
116 >     * @param initialElements the collection whose elements are to be placed
117 >     *        into this priority queue.
118 >     * @throws ClassCastException if elements of the specified collection
119 >     *         cannot be compared to one another according to the priority
120 >     *         queue's ordering.
121 >     * @throws NullPointerException if the specified collection or an
122 >     *         element of the specified collection is <tt>null</tt>.
123 >     */
124 >    public PriorityQueue(Collection<E> initialElements) {
125 >        int sz = initialElements.size();
126 >        int initialCapacity = (int)Math.min((sz * 110L) / 100,
127 >                                            Integer.MAX_VALUE - 1);
128 >        if (initialCapacity < 1)
129 >            initialCapacity = 1;
130 >        queue = new E[initialCapacity + 1];
131 >
132 >        /* Commented out to compile with generics compiler
133 >
134 >        if (initialElements instanceof Sorted) {
135 >            comparator = ((Sorted)initialElements).comparator();
136 >            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
137 >                queue[++size] = i.next();
138 >        } else {
139 >        */
140 >        {
141 >            comparator = null;
142 >            for (Iterator<E> i = initialElements.iterator(); i.hasNext(); )
143 >                add(i.next());
144 >        }
145      }
146 +
147 +    // Queue Methods
148 +
149 +    /**
150 +     * Remove and return the minimal element from this priority queue if
151 +     * it contains one or more elements, otherwise <tt>null</tt>.  The term
152 +     * <i>minimal</i> is defined according to this priority queue's order.
153 +     *
154 +     * @return the minimal element from this priority queue if it contains
155 +     *         one or more elements, otherwise <tt>null</tt>.
156 +     */
157      public E poll() {
158 <        return null;
158 >        if (size == 0)
159 >            return null;
160 >        return remove(1);
161      }
162 +
163 +    /**
164 +     * Return, but do not remove, the minimal element from the priority queue,
165 +     * or <tt>null</tt> if the queue is empty.  The term <i>minimal</i> is
166 +     * defined according to this priority queue's order.  This method returns
167 +     * the same object reference that would be returned by by the
168 +     * <tt>poll</tt> method.  The two methods differ in that this method
169 +     * does not remove the element from the priority queue.
170 +     *
171 +     * @return the minimal element from this priority queue if it contains
172 +     *         one or more elements, otherwise <tt>null</tt>.
173 +     */
174      public E peek() {
175 <        return null;
175 >        return queue[1];
176      }
177  
178 <    public boolean isEmpty() {
178 >    // Collection Methods
179 >
180 >    /**
181 >     * Removes a single instance of the specified element from this priority
182 >     * queue, if it is present.  Returns true if this collection contained the
183 >     * specified element (or equivalently, if this collection changed as a
184 >     * result of the call).
185 >     *
186 >     * @param o element to be removed from this collection, if present.
187 >     * @return <tt>true</tt> if this collection changed as a result of the
188 >     *         call
189 >     * @throws ClassCastException if the specified element cannot be compared
190 >     *            with elements currently in the priority queue according
191 >     *            to the priority queue's ordering.
192 >     * @throws NullPointerException if the specified element is null.
193 >     */
194 >    public boolean remove(Object element) {
195 >        if (element == null)
196 >            throw new NullPointerException();
197 >
198 >        if (comparator == null) {
199 >            for (int i = 1; i <= size; i++) {
200 >                if (((Comparable)queue[i]).compareTo(element) == 0) {
201 >                    remove(i);
202 >                    return true;
203 >                }
204 >            }
205 >        } else {
206 >            for (int i = 1; i <= size; i++) {
207 >                if (comparator.compare(queue[i], (E) element) == 0) {
208 >                    remove(i);
209 >                    return true;
210 >                }
211 >            }
212 >        }
213          return false;
214      }
215 +
216 +    /**
217 +     * Returns an iterator over the elements in this priority queue.  The
218 +     * first element returned by this iterator is the same element that
219 +     * would be returned by a call to <tt>peek</tt>.
220 +     *
221 +     * @return an <tt>Iterator</tt> over the elements in this priority queue.
222 +     */
223 +    public Iterator<E> iterator() {
224 +        return new Itr();
225 +    }
226 +
227 +    private class Itr implements Iterator<E> {
228 +        /**
229 +         * Index (into queue array) of element to be returned by
230 +         * subsequent call to next.
231 +         */
232 +        int cursor = 1;
233 +
234 +        /**
235 +         * Index of element returned by most recent call to next or
236 +         * previous.  Reset to 0 if this element is deleted by a call
237 +         * to remove.
238 +         */
239 +        int lastRet = 0;
240 +
241 +        /**
242 +         * The modCount value that the iterator believes that the backing
243 +         * List should have.  If this expectation is violated, the iterator
244 +         * has detected concurrent modification.
245 +         */
246 +        int expectedModCount = modCount;
247 +
248 +        public boolean hasNext() {
249 +            return cursor <= size;
250 +        }
251 +
252 +        public E next() {
253 +            checkForComodification();
254 +            if (cursor > size)
255 +                throw new NoSuchElementException();
256 +            E result = queue[cursor];
257 +            lastRet = cursor++;
258 +            return result;
259 +        }
260 +
261 +        public void remove() {
262 +            if (lastRet == 0)
263 +                throw new IllegalStateException();
264 +            checkForComodification();
265 +
266 +            PriorityQueue.this.remove(lastRet);
267 +            if (lastRet < cursor)
268 +                cursor--;
269 +            lastRet = 0;
270 +            expectedModCount = modCount;
271 +        }
272 +
273 +        final void checkForComodification() {
274 +            if (modCount != expectedModCount)
275 +                throw new ConcurrentModificationException();
276 +        }
277 +    }
278 +
279 +    /**
280 +     * Returns the number of elements in this priority queue.
281 +     *
282 +     * @return the number of elements in this priority queue.
283 +     */
284      public int size() {
285 <        return 0;
285 >        return size;
286      }
287 <    public Object[] toArray() {
288 <        return null;
287 >
288 >    /**
289 >     * Add the specified element to this priority queue.
290 >     *
291 >     * @param element the element to add.
292 >     * @return true
293 >     * @throws ClassCastException if the specified element cannot be compared
294 >     *            with elements currently in the priority queue according
295 >     *            to the priority queue's ordering.
296 >     * @throws NullPointerException if the specified element is null.
297 >     */
298 >    public boolean offer(E element) {
299 >        if (element == null)
300 >            throw new NullPointerException();
301 >        modCount++;
302 >
303 >        // Grow backing store if necessary
304 >        if (++size == queue.length) {
305 >            E[] newQueue = new E[2 * queue.length];
306 >            System.arraycopy(queue, 0, newQueue, 0, size);
307 >            queue = newQueue;
308 >        }
309 >
310 >        queue[size] = element;
311 >        fixUp(size);
312 >        return true;
313      }
314  
315 <    public <T> T[] toArray(T[] array) {
316 <        return null;
315 >    /**
316 >     * Remove all elements from the priority queue.
317 >     */
318 >    public void clear() {
319 >        modCount++;
320 >
321 >        // Null out element references to prevent memory leak
322 >        for (int i=1; i<=size; i++)
323 >            queue[i] = null;
324 >
325 >        size = 0;
326 >    }
327 >
328 >    /**
329 >     * Removes and returns the ith element from queue.  Recall
330 >     * that queue is one-based, so 1 <= i <= size.
331 >     *
332 >     * XXX: Could further special-case i==size, but is it worth it?
333 >     * XXX: Could special-case i==0, but is it worth it?
334 >     */
335 >    private E remove(int i) {
336 >        assert i <= size;
337 >        modCount++;
338 >
339 >        E result = queue[i];
340 >        queue[i] = queue[size];
341 >        queue[size--] = null;  // Drop extra ref to prevent memory leak
342 >        if (i <= size)
343 >            fixDown(i);
344 >        return result;
345      }
346  
347 +    /**
348 +     * Establishes the heap invariant (described above) assuming the heap
349 +     * satisfies the invariant except possibly for the leaf-node indexed by k
350 +     * (which may have a nextExecutionTime less than its parent's).
351 +     *
352 +     * This method functions by "promoting" queue[k] up the hierarchy
353 +     * (by swapping it with its parent) repeatedly until queue[k]
354 +     * is greater than or equal to its parent.
355 +     */
356 +    private void fixUp(int k) {
357 +        if (comparator == null) {
358 +            while (k > 1) {
359 +                int j = k >> 1;
360 +                if (((Comparable)queue[j]).compareTo(queue[k]) <= 0)
361 +                    break;
362 +                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
363 +                k = j;
364 +            }
365 +        } else {
366 +            while (k > 1) {
367 +                int j = k >> 1;
368 +                if (comparator.compare(queue[j], queue[k]) <= 0)
369 +                    break;
370 +                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
371 +                k = j;
372 +            }
373 +        }
374 +    }
375 +
376 +    /**
377 +     * Establishes the heap invariant (described above) in the subtree
378 +     * rooted at k, which is assumed to satisfy the heap invariant except
379 +     * possibly for node k itself (which may be greater than its children).
380 +     *
381 +     * This method functions by "demoting" queue[k] down the hierarchy
382 +     * (by swapping it with its smaller child) repeatedly until queue[k]
383 +     * is less than or equal to its children.
384 +     */
385 +    private void fixDown(int k) {
386 +        int j;
387 +        if (comparator == null) {
388 +            while ((j = k << 1) <= size) {
389 +                if (j<size && ((Comparable)queue[j]).compareTo(queue[j+1]) > 0)
390 +                    j++; // j indexes smallest kid
391 +                if (((Comparable)queue[k]).compareTo(queue[j]) <= 0)
392 +                    break;
393 +                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
394 +                k = j;
395 +            }
396 +        } else {
397 +            while ((j = k << 1) <= size) {
398 +                if (j < size && comparator.compare(queue[j], queue[j+1]) > 0)
399 +                    j++; // j indexes smallest kid
400 +                if (comparator.compare(queue[k], queue[j]) <= 0)
401 +                    break;
402 +                E tmp = queue[j];  queue[j] = queue[k]; queue[k] = tmp;
403 +                k = j;
404 +            }
405 +        }
406 +    }
407 +
408 +    /**
409 +     * Returns the comparator associated with this priority queue, or
410 +     * <tt>null</tt> if it uses its elements' natural ordering.
411 +     *
412 +     * @return the comparator associated with this priority queue, or
413 +     *         <tt>null</tt> if it uses its elements' natural ordering.
414 +     */
415 +    Comparator comparator() {
416 +        return comparator;
417 +    }
418   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines