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