1 |
|
package java.util; |
2 |
|
|
3 |
– |
/* |
4 |
– |
* Todo |
5 |
– |
* |
6 |
– |
* 1) Make it serializable. |
7 |
– |
*/ |
8 |
– |
|
3 |
|
/** |
4 |
< |
* An unbounded priority queue based on a priority heap. This queue orders |
5 |
< |
* elements according to the order specified at creation time. This order is |
6 |
< |
* specified as for {@link TreeSet} and {@link TreeMap}: Elements are ordered |
7 |
< |
* 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 |
< |
* these elements are tied for least value, no guarantees are made as to |
12 |
< |
* which of elements is returned. |
4 |
> |
* An unbounded priority {@linkplain Queue queue} based on a priority heap. |
5 |
> |
* This queue orders elements according to an order specified at construction |
6 |
> |
* time, which is specified in the same manner as {@link java.util.TreeSet} |
7 |
> |
* and {@link java.util.TreeMap}: elements are ordered either according to |
8 |
> |
* their <i>natural order</i> (see {@link Comparable}), or according to a |
9 |
> |
* {@link java.util.Comparator}, depending on which constructor is used. |
10 |
> |
* <p>The <em>head</em> of this queue is the <em>least</em> element with |
11 |
> |
* respect to the specified ordering. If multiple elements are tied for least |
12 |
> |
* value, the 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. |
17 |
> |
* |
18 |
> |
* <p>The {@link #element()} and {@link #peek()} methods return, but do |
19 |
> |
* not delete, the head of the queue. |
20 |
|
* |
21 |
< |
* <p>Each priority queue has a <i>capacity</i>. The capacity is the size of |
22 |
< |
* the array used to store the elements on the queue. It is always at least |
23 |
< |
* as large as the queue size. As elements are added to a priority list, |
24 |
< |
* its capacity grows automatically. The details of the growth policy are not |
25 |
< |
* specified. |
21 |
> |
* <p>A priority queue has a <i>capacity</i>. The capacity is the |
22 |
> |
* size of the array used internally to store the elements on the |
23 |
> |
* queue. |
24 |
> |
* It is always at least as large as the queue size. As |
25 |
> |
* elements are added to a priority queue, its capacity grows |
26 |
> |
* automatically. The details of the growth policy are not specified. |
27 |
|
* |
28 |
< |
*<p>Implementation note: this implementation provides O(log(n)) time for |
29 |
< |
* the <tt>offer</tt>, <tt>poll</tt>, <tt>remove()</tt> and <tt>add</tt> |
30 |
< |
* methods; linear time for the <tt>remove(Object)</tt> and |
31 |
< |
* <tt>contains</tt> methods; and constant time for the <tt>peek</tt>, |
32 |
< |
* <tt>element</tt>, and <tt>size</tt> methods. |
28 |
> |
* <p>The Iterator provided in method {@link #iterator()} is <em>not</em> |
29 |
> |
* guaranteed to traverse the elements of the PriorityQueue in any |
30 |
> |
* particular order. If you need ordered traversal, consider using |
31 |
> |
* <tt>Arrays.sort(pq.toArray())</tt>. |
32 |
> |
* |
33 |
> |
* <p> <strong>Note that this implementation is not synchronized.</strong> |
34 |
> |
* Multiple threads should not access a <tt>PriorityQueue</tt> |
35 |
> |
* instance concurrently if any of the threads modifies the list |
36 |
> |
* structurally. Instead, use the thread-safe {@link |
37 |
> |
* java.util.concurrent.PriorityBlockingQueue} class. |
38 |
> |
* |
39 |
> |
* |
40 |
> |
* <p>Implementation note: this implementation provides O(log(n)) time |
41 |
> |
* for the insertion methods (<tt>offer</tt>, <tt>poll</tt>, |
42 |
> |
* <tt>remove()</tt> and <tt>add</tt>) methods; linear time for the |
43 |
> |
* <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and |
44 |
> |
* constant time for the retrieval methods (<tt>peek</tt>, |
45 |
> |
* <tt>element</tt>, and <tt>size</tt>). |
46 |
|
* |
47 |
|
* <p>This class is a member of the |
48 |
|
* <a href="{@docRoot}/../guide/collections/index.html"> |
49 |
|
* Java Collections Framework</a>. |
50 |
+ |
* @since 1.5 |
51 |
+ |
* @author Josh Bloch |
52 |
|
*/ |
53 |
|
public class PriorityQueue<E> extends AbstractQueue<E> |
54 |
< |
implements Queue<E> |
55 |
< |
{ |
54 |
> |
implements Queue<E>, java.io.Serializable { |
55 |
> |
|
56 |
> |
private static final long serialVersionUID = -7720805057305804111L; |
57 |
> |
|
58 |
|
private static final int DEFAULT_INITIAL_CAPACITY = 11; |
59 |
|
|
60 |
|
/** |
61 |
|
* Priority queue represented as a balanced binary heap: the two children |
62 |
|
* of queue[n] are queue[2*n] and queue[2*n + 1]. The priority queue is |
63 |
|
* ordered by comparator, or by the elements' natural ordering, if |
64 |
< |
* comparator is null: For each node n in the heap, and each descendant |
65 |
< |
* of n, d, n <= d. |
64 |
> |
* comparator is null: For each node n in the heap and each descendant d |
65 |
> |
* of n, n <= d. |
66 |
|
* |
67 |
< |
* The element with the lowest value is in queue[1] (assuming the queue is |
68 |
< |
* nonempty). A one-based array is used in preference to the traditional |
69 |
< |
* zero-based array to simplify parent and child calculations. |
67 |
> |
* The element with the lowest value is in queue[1], assuming the queue is |
68 |
> |
* nonempty. (A one-based array is used in preference to the traditional |
69 |
> |
* zero-based array to simplify parent and child calculations.) |
70 |
|
* |
71 |
|
* queue.length must be >= 2, even if size == 0. |
72 |
|
*/ |
73 |
< |
private E[] queue; |
73 |
> |
private transient Object[] queue; |
74 |
|
|
75 |
|
/** |
76 |
|
* The number of elements in the priority queue. |
81 |
|
* The comparator, or null if priority queue uses elements' |
82 |
|
* natural ordering. |
83 |
|
*/ |
84 |
< |
private final Comparator<E> comparator; |
84 |
> |
private final Comparator<? super E> comparator; |
85 |
|
|
86 |
|
/** |
87 |
|
* The number of times this priority queue has been |
88 |
|
* <i>structurally modified</i>. See AbstractList for gory details. |
89 |
|
*/ |
90 |
< |
private int modCount = 0; |
90 |
> |
private transient int modCount = 0; |
91 |
|
|
92 |
|
/** |
93 |
< |
* Create a new priority queue with the default initial capacity (11) |
94 |
< |
* that orders its elements according to their natural ordering. |
93 |
> |
* Creates a <tt>PriorityQueue</tt> with the default initial capacity |
94 |
> |
* (11) that orders its elements according to their natural |
95 |
> |
* ordering (using <tt>Comparable</tt>). |
96 |
|
*/ |
97 |
|
public PriorityQueue() { |
98 |
< |
this(DEFAULT_INITIAL_CAPACITY); |
98 |
> |
this(DEFAULT_INITIAL_CAPACITY, null); |
99 |
|
} |
100 |
|
|
101 |
|
/** |
102 |
< |
* Create a new priority queue with the specified initial capacity |
103 |
< |
* that orders its elements according to their natural ordering. |
102 |
> |
* Creates a <tt>PriorityQueue</tt> with the specified initial capacity |
103 |
> |
* that orders its elements according to their natural ordering |
104 |
> |
* (using <tt>Comparable</tt>). |
105 |
|
* |
106 |
|
* @param initialCapacity the initial capacity for this priority queue. |
107 |
+ |
* @throws IllegalArgumentException if <tt>initialCapacity</tt> is less |
108 |
+ |
* than 1 |
109 |
|
*/ |
110 |
|
public PriorityQueue(int initialCapacity) { |
111 |
|
this(initialCapacity, null); |
112 |
|
} |
113 |
|
|
114 |
|
/** |
115 |
< |
* Create a new priority queue with the specified initial capacity (11) |
115 |
> |
* Creates a <tt>PriorityQueue</tt> with the specified initial capacity |
116 |
|
* that orders its elements according to the specified comparator. |
117 |
|
* |
118 |
|
* @param initialCapacity the initial capacity for this priority queue. |
119 |
|
* @param comparator the comparator used to order this priority queue. |
120 |
+ |
* If <tt>null</tt> then the order depends on the elements' natural |
121 |
+ |
* ordering. |
122 |
+ |
* @throws IllegalArgumentException if <tt>initialCapacity</tt> is less |
123 |
+ |
* than 1 |
124 |
|
*/ |
125 |
< |
public PriorityQueue(int initialCapacity, Comparator<E> comparator) { |
125 |
> |
public PriorityQueue(int initialCapacity, |
126 |
> |
Comparator<? super E> comparator) { |
127 |
|
if (initialCapacity < 1) |
128 |
< |
initialCapacity = 1; |
129 |
< |
queue = new E[initialCapacity + 1]; |
128 |
> |
throw new IllegalArgumentException(); |
129 |
> |
this.queue = new Object[initialCapacity + 1]; |
130 |
|
this.comparator = comparator; |
131 |
|
} |
132 |
|
|
133 |
|
/** |
134 |
< |
* Create a new priority queue containing the elements in the specified |
135 |
< |
* 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>. |
134 |
> |
* Common code to initialize underlying queue array across |
135 |
> |
* constructors below. |
136 |
|
*/ |
137 |
< |
public PriorityQueue(Collection<E> initialElements) { |
138 |
< |
int sz = initialElements.size(); |
137 |
> |
private void initializeArray(Collection<? extends E> c) { |
138 |
> |
int sz = c.size(); |
139 |
|
int initialCapacity = (int)Math.min((sz * 110L) / 100, |
140 |
|
Integer.MAX_VALUE - 1); |
141 |
|
if (initialCapacity < 1) |
142 |
|
initialCapacity = 1; |
130 |
– |
queue = new E[initialCapacity + 1]; |
143 |
|
|
144 |
< |
if (initialElements instanceof Sorted) { |
145 |
< |
comparator = ((Sorted)initialElements).comparator(); |
146 |
< |
for (Iterator<E> i = initialElements.iterator(); i.hasNext(); ) |
147 |
< |
queue[++size] = i.next(); |
144 |
> |
this.queue = new Object[initialCapacity + 1]; |
145 |
> |
} |
146 |
> |
|
147 |
> |
/** |
148 |
> |
* Initially fill elements of the queue array under the |
149 |
> |
* knowledge that it is sorted or is another PQ, in which |
150 |
> |
* case we can just place the elements in the order presented. |
151 |
> |
*/ |
152 |
> |
private void fillFromSorted(Collection<? extends E> c) { |
153 |
> |
for (Iterator<? extends E> i = c.iterator(); i.hasNext(); ) |
154 |
> |
queue[++size] = i.next(); |
155 |
> |
} |
156 |
> |
|
157 |
> |
/** |
158 |
> |
* Initially fill elements of the queue array that is not to our knowledge |
159 |
> |
* sorted, so we must rearrange the elements to guarantee the heap |
160 |
> |
* invariant. |
161 |
> |
*/ |
162 |
> |
private void fillFromUnsorted(Collection<? extends E> c) { |
163 |
> |
for (Iterator<? extends E> i = c.iterator(); i.hasNext(); ) |
164 |
> |
queue[++size] = i.next(); |
165 |
> |
heapify(); |
166 |
> |
} |
167 |
> |
|
168 |
> |
/** |
169 |
> |
* Creates a <tt>PriorityQueue</tt> containing the elements in the |
170 |
> |
* specified collection. The priority queue has an initial |
171 |
> |
* capacity of 110% of the size of the specified collection or 1 |
172 |
> |
* if the collection is empty. If the specified collection is an |
173 |
> |
* instance of a {@link java.util.SortedSet} or is another |
174 |
> |
* <tt>PriorityQueue</tt>, the priority queue will be sorted |
175 |
> |
* according to the same comparator, or according to its elements' |
176 |
> |
* natural order if the collection is sorted according to its |
177 |
> |
* elements' natural order. Otherwise, the priority queue is |
178 |
> |
* ordered according to its elements' natural order. |
179 |
> |
* |
180 |
> |
* @param c the collection whose elements are to be placed |
181 |
> |
* into this priority queue. |
182 |
> |
* @throws ClassCastException if elements of the specified collection |
183 |
> |
* cannot be compared to one another according to the priority |
184 |
> |
* queue's ordering. |
185 |
> |
* @throws NullPointerException if <tt>c</tt> or any element within it |
186 |
> |
* is <tt>null</tt> |
187 |
> |
*/ |
188 |
> |
public PriorityQueue(Collection<? extends E> c) { |
189 |
> |
initializeArray(c); |
190 |
> |
if (c instanceof SortedSet) { |
191 |
> |
// @fixme double-cast workaround for compiler |
192 |
> |
SortedSet<? extends E> s = (SortedSet<? extends E>) (SortedSet)c; |
193 |
> |
comparator = (Comparator<? super E>)s.comparator(); |
194 |
> |
fillFromSorted(s); |
195 |
> |
} else if (c instanceof PriorityQueue) { |
196 |
> |
PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c; |
197 |
> |
comparator = (Comparator<? super E>)s.comparator(); |
198 |
> |
fillFromSorted(s); |
199 |
|
} else { |
200 |
|
comparator = null; |
201 |
< |
for (Iterator<E> i = initialElements.iterator(); i.hasNext(); ) |
139 |
< |
add(i.next()); |
201 |
> |
fillFromUnsorted(c); |
202 |
|
} |
203 |
|
} |
204 |
|
|
205 |
+ |
/** |
206 |
+ |
* Creates a <tt>PriorityQueue</tt> containing the elements in the |
207 |
+ |
* specified collection. The priority queue has an initial |
208 |
+ |
* capacity of 110% of the size of the specified collection or 1 |
209 |
+ |
* if the collection is empty. This priority queue will be sorted |
210 |
+ |
* according to the same comparator as the given collection, or |
211 |
+ |
* according to its elements' natural order if the collection is |
212 |
+ |
* sorted according to its elements' natural order. |
213 |
+ |
* |
214 |
+ |
* @param c the collection whose elements are to be placed |
215 |
+ |
* into this priority queue. |
216 |
+ |
* @throws ClassCastException if elements of the specified collection |
217 |
+ |
* cannot be compared to one another according to the priority |
218 |
+ |
* queue's ordering. |
219 |
+ |
* @throws NullPointerException if <tt>c</tt> or any element within it |
220 |
+ |
* is <tt>null</tt> |
221 |
+ |
*/ |
222 |
+ |
public PriorityQueue(PriorityQueue<? extends E> c) { |
223 |
+ |
initializeArray(c); |
224 |
+ |
comparator = (Comparator<? super E>)c.comparator(); |
225 |
+ |
fillFromSorted(c); |
226 |
+ |
} |
227 |
+ |
|
228 |
+ |
/** |
229 |
+ |
* Creates a <tt>PriorityQueue</tt> containing the elements in the |
230 |
+ |
* specified collection. The priority queue has an initial |
231 |
+ |
* capacity of 110% of the size of the specified collection or 1 |
232 |
+ |
* if the collection is empty. This priority queue will be sorted |
233 |
+ |
* according to the same comparator as the given collection, or |
234 |
+ |
* according to its elements' natural order if the collection is |
235 |
+ |
* sorted according to its elements' natural order. |
236 |
+ |
* |
237 |
+ |
* @param c the collection whose elements are to be placed |
238 |
+ |
* into this priority queue. |
239 |
+ |
* @throws ClassCastException if elements of the specified collection |
240 |
+ |
* cannot be compared to one another according to the priority |
241 |
+ |
* queue's ordering. |
242 |
+ |
* @throws NullPointerException if <tt>c</tt> or any element within it |
243 |
+ |
* is <tt>null</tt> |
244 |
+ |
*/ |
245 |
+ |
public PriorityQueue(SortedSet<? extends E> c) { |
246 |
+ |
initializeArray(c); |
247 |
+ |
comparator = (Comparator<? super E>)c.comparator(); |
248 |
+ |
fillFromSorted(c); |
249 |
+ |
} |
250 |
+ |
|
251 |
+ |
/** |
252 |
+ |
* Resize array, if necessary, to be able to hold given index |
253 |
+ |
*/ |
254 |
+ |
private void grow(int index) { |
255 |
+ |
int newlen = queue.length; |
256 |
+ |
if (index < newlen) // don't need to grow |
257 |
+ |
return; |
258 |
+ |
if (index == Integer.MAX_VALUE) |
259 |
+ |
throw new OutOfMemoryError(); |
260 |
+ |
while (newlen <= index) { |
261 |
+ |
if (newlen >= Integer.MAX_VALUE / 2) // avoid overflow |
262 |
+ |
newlen = Integer.MAX_VALUE; |
263 |
+ |
else |
264 |
+ |
newlen <<= 2; |
265 |
+ |
} |
266 |
+ |
Object[] newQueue = new Object[newlen]; |
267 |
+ |
System.arraycopy(queue, 0, newQueue, 0, queue.length); |
268 |
+ |
queue = newQueue; |
269 |
+ |
} |
270 |
+ |
|
271 |
+ |
|
272 |
|
// Queue Methods |
273 |
|
|
274 |
|
/** |
275 |
< |
* Remove and return the minimal element from this priority queue if |
147 |
< |
* it contains one or more elements, otherwise <tt>null</tt>. The term |
148 |
< |
* <i>minimal</i> is defined according to this priority queue's order. |
275 |
> |
* Add the specified element to this priority queue. |
276 |
|
* |
277 |
< |
* @return the minimal element from this priority queue if it contains |
278 |
< |
* one or more elements, otherwise <tt>null</tt>. |
277 |
> |
* @return <tt>true</tt> |
278 |
> |
* @throws ClassCastException if the specified element cannot be compared |
279 |
> |
* with elements currently in the priority queue according |
280 |
> |
* to the priority queue's ordering. |
281 |
> |
* @throws NullPointerException if the specified element is <tt>null</tt>. |
282 |
|
*/ |
283 |
+ |
public boolean offer(E o) { |
284 |
+ |
if (o == null) |
285 |
+ |
throw new NullPointerException(); |
286 |
+ |
modCount++; |
287 |
+ |
++size; |
288 |
+ |
|
289 |
+ |
// Grow backing store if necessary |
290 |
+ |
if (size >= queue.length) |
291 |
+ |
grow(size); |
292 |
+ |
|
293 |
+ |
queue[size] = o; |
294 |
+ |
fixUp(size); |
295 |
+ |
return true; |
296 |
+ |
} |
297 |
+ |
|
298 |
|
public E poll() { |
299 |
|
if (size == 0) |
300 |
|
return null; |
301 |
< |
return remove(1); |
301 |
> |
return remove(); |
302 |
> |
} |
303 |
> |
|
304 |
> |
public E peek() { |
305 |
> |
return (E) queue[1]; |
306 |
|
} |
307 |
|
|
308 |
+ |
// Collection Methods - the first two override to update docs |
309 |
+ |
|
310 |
|
/** |
311 |
< |
* Return, but do not remove, the minimal element from the priority queue, |
312 |
< |
* or <tt>null</tt> if the queue is empty. The term <i>minimal</i> is |
313 |
< |
* defined according to this priority queue's order. This method returns |
163 |
< |
* the same object reference that would be returned by by the |
164 |
< |
* <tt>poll</tt> method. The two methods differ in that this method |
165 |
< |
* does not remove the element from the priority queue. |
311 |
> |
* Adds the specified element to this queue. |
312 |
> |
* @return <tt>true</tt> (as per the general contract of |
313 |
> |
* <tt>Collection.add</tt>). |
314 |
|
* |
315 |
< |
* @return the minimal element from this priority queue if it contains |
316 |
< |
* one or more elements, otherwise <tt>null</tt>. |
315 |
> |
* @throws NullPointerException {@inheritDoc} |
316 |
> |
* @throws ClassCastException if the specified element cannot be compared |
317 |
> |
* with elements currently in the priority queue according |
318 |
> |
* to the priority queue's ordering. |
319 |
|
*/ |
320 |
< |
public E peek() { |
321 |
< |
return queue[1]; |
320 |
> |
public boolean add(E o) { |
321 |
> |
return super.add(o); |
322 |
> |
} |
323 |
> |
|
324 |
> |
|
325 |
> |
/** |
326 |
> |
* Adds all of the elements in the specified collection to this queue. |
327 |
> |
* The behavior of this operation is undefined if |
328 |
> |
* the specified collection is modified while the operation is in |
329 |
> |
* progress. (This implies that the behavior of this call is undefined if |
330 |
> |
* the specified collection is this queue, and this queue is nonempty.) |
331 |
> |
* <p> |
332 |
> |
* This implementation iterates over the specified collection, and adds |
333 |
> |
* each object returned by the iterator to this collection, in turn. |
334 |
> |
* @throws NullPointerException {@inheritDoc} |
335 |
> |
* @throws ClassCastException if any element cannot be compared |
336 |
> |
* with elements currently in the priority queue according |
337 |
> |
* to the priority queue's ordering. |
338 |
> |
*/ |
339 |
> |
public boolean addAll(Collection<? extends E> c) { |
340 |
> |
return super.addAll(c); |
341 |
|
} |
342 |
|
|
174 |
– |
// Collection Methods |
343 |
|
|
344 |
|
/** |
345 |
< |
* Removes a single instance of the specified element from this priority |
346 |
< |
* queue, if it is present. Returns true if this collection contained the |
347 |
< |
* specified element (or equivalently, if this collection changed as a |
345 |
> |
* Removes a single instance of the specified element from this |
346 |
> |
* queue, if it is present. More formally, |
347 |
> |
* removes an element <tt>e</tt> such that <tt>(o==null ? e==null : |
348 |
> |
* o.equals(e))</tt>, if the queue contains one or more such |
349 |
> |
* elements. Returns <tt>true</tt> if the queue contained the |
350 |
> |
* specified element (or equivalently, if the queue changed as a |
351 |
|
* result of the call). |
352 |
|
* |
353 |
< |
* @param o element to be removed from this collection, if present. |
354 |
< |
* @return <tt>true</tt> if this collection changed as a result of the |
355 |
< |
* call |
356 |
< |
* @throws ClassCastException if the specified element cannot be compared |
186 |
< |
* with elements currently in the priority queue according |
187 |
< |
* to the priority queue's ordering. |
188 |
< |
* @throws NullPointerException if the specified element is null. |
353 |
> |
* <p>This implementation iterates over the queue looking for the |
354 |
> |
* specified element. If it finds the element, it removes the element |
355 |
> |
* from the queue using the iterator's remove method.<p> |
356 |
> |
* |
357 |
|
*/ |
358 |
< |
public boolean remove(Object element) { |
359 |
< |
if (element == null) |
360 |
< |
throw new NullPointerException(); |
358 |
> |
public boolean remove(Object o) { |
359 |
> |
if (o == null) |
360 |
> |
return false; |
361 |
|
|
362 |
|
if (comparator == null) { |
363 |
|
for (int i = 1; i <= size; i++) { |
364 |
< |
if (((Comparable)queue[i]).compareTo(element) == 0) { |
365 |
< |
remove(i); |
364 |
> |
if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) { |
365 |
> |
removeAt(i); |
366 |
|
return true; |
367 |
|
} |
368 |
|
} |
369 |
|
} else { |
370 |
|
for (int i = 1; i <= size; i++) { |
371 |
< |
if (comparator.compare(queue[i], (E) element) == 0) { |
372 |
< |
remove(i); |
371 |
> |
if (comparator.compare((E)queue[i], (E)o) == 0) { |
372 |
> |
removeAt(i); |
373 |
|
return true; |
374 |
|
} |
375 |
|
} |
378 |
|
} |
379 |
|
|
380 |
|
/** |
381 |
< |
* Returns an iterator over the elements in this priority queue. The |
382 |
< |
* first element returned by this iterator is the same element that |
215 |
< |
* would be returned by a call to <tt>peek</tt>. |
381 |
> |
* Returns an iterator over the elements in this queue. The iterator |
382 |
> |
* does not return the elements in any particular order. |
383 |
|
* |
384 |
< |
* @return an <tt>Iterator</tt> over the elements in this priority queue. |
384 |
> |
* @return an iterator over the elements in this queue. |
385 |
|
*/ |
386 |
|
public Iterator<E> iterator() { |
387 |
|
return new Itr(); |
388 |
|
} |
389 |
|
|
390 |
|
private class Itr implements Iterator<E> { |
391 |
+ |
|
392 |
|
/** |
393 |
|
* Index (into queue array) of element to be returned by |
394 |
|
* subsequent call to next. |
395 |
|
*/ |
396 |
< |
int cursor = 1; |
396 |
> |
private int cursor = 1; |
397 |
|
|
398 |
|
/** |
399 |
< |
* Index of element returned by most recent call to next or |
400 |
< |
* previous. Reset to 0 if this element is deleted by a call |
401 |
< |
* to remove. |
399 |
> |
* Index of element returned by most recent call to next, |
400 |
> |
* unless that element came from the forgetMeNot list. |
401 |
> |
* Reset to 0 if element is deleted by a call to remove. |
402 |
|
*/ |
403 |
< |
int lastRet = 0; |
403 |
> |
private int lastRet = 0; |
404 |
|
|
405 |
|
/** |
406 |
|
* The modCount value that the iterator believes that the backing |
407 |
|
* List should have. If this expectation is violated, the iterator |
408 |
|
* has detected concurrent modification. |
409 |
|
*/ |
410 |
< |
int expectedModCount = modCount; |
410 |
> |
private int expectedModCount = modCount; |
411 |
> |
|
412 |
> |
/** |
413 |
> |
* A list of elements that were moved from the unvisited portion of |
414 |
> |
* the heap into the visited portion as a result of "unlucky" element |
415 |
> |
* removals during the iteration. (Unlucky element removals are those |
416 |
> |
* that require a fixup instead of a fixdown.) We must visit all of |
417 |
> |
* the elements in this list to complete the iteration. We do this |
418 |
> |
* after we've completed the "normal" iteration. |
419 |
> |
* |
420 |
> |
* We expect that most iterations, even those involving removals, |
421 |
> |
* will not use need to store elements in this field. |
422 |
> |
*/ |
423 |
> |
private ArrayList<E> forgetMeNot = null; |
424 |
> |
|
425 |
> |
/** |
426 |
> |
* Element returned by the most recent call to next iff that |
427 |
> |
* element was drawn from the forgetMeNot list. |
428 |
> |
*/ |
429 |
> |
private Object lastRetElt = null; |
430 |
|
|
431 |
|
public boolean hasNext() { |
432 |
< |
return cursor <= size; |
432 |
> |
return cursor <= size || forgetMeNot != null; |
433 |
|
} |
434 |
|
|
435 |
|
public E next() { |
436 |
|
checkForComodification(); |
437 |
< |
if (cursor > size) |
437 |
> |
E result; |
438 |
> |
if (cursor <= size) { |
439 |
> |
result = (E) queue[cursor]; |
440 |
> |
lastRet = cursor++; |
441 |
> |
} |
442 |
> |
else if (forgetMeNot == null) |
443 |
|
throw new NoSuchElementException(); |
444 |
< |
E result = queue[cursor]; |
445 |
< |
lastRet = cursor++; |
444 |
> |
else { |
445 |
> |
int remaining = forgetMeNot.size(); |
446 |
> |
result = forgetMeNot.remove(remaining - 1); |
447 |
> |
if (remaining == 1) |
448 |
> |
forgetMeNot = null; |
449 |
> |
lastRet = 0; |
450 |
> |
lastRetElt = result; |
451 |
> |
} |
452 |
|
return result; |
453 |
|
} |
454 |
|
|
455 |
|
public void remove() { |
258 |
– |
if (lastRet == 0) |
259 |
– |
throw new IllegalStateException(); |
456 |
|
checkForComodification(); |
457 |
|
|
458 |
< |
PriorityQueue.this.remove(lastRet); |
459 |
< |
if (lastRet < cursor) |
460 |
< |
cursor--; |
461 |
< |
lastRet = 0; |
458 |
> |
if (lastRet != 0) { |
459 |
> |
E moved = PriorityQueue.this.removeAt(lastRet); |
460 |
> |
lastRet = 0; |
461 |
> |
if (moved == null) { |
462 |
> |
cursor--; |
463 |
> |
} else { |
464 |
> |
if (forgetMeNot == null) |
465 |
> |
forgetMeNot = new ArrayList<E>(); |
466 |
> |
forgetMeNot.add(moved); |
467 |
> |
} |
468 |
> |
} else if (lastRetElt != null) { |
469 |
> |
PriorityQueue.this.remove(lastRetElt); |
470 |
> |
lastRetElt = null; |
471 |
> |
} else { |
472 |
> |
throw new IllegalStateException(); |
473 |
> |
} |
474 |
> |
|
475 |
|
expectedModCount = modCount; |
476 |
|
} |
477 |
|
|
481 |
|
} |
482 |
|
} |
483 |
|
|
275 |
– |
/** |
276 |
– |
* Returns the number of elements in this priority queue. |
277 |
– |
* |
278 |
– |
* @return the number of elements in this priority queue. |
279 |
– |
*/ |
484 |
|
public int size() { |
485 |
|
return size; |
486 |
|
} |
487 |
|
|
488 |
|
/** |
489 |
< |
* Add the specified element to this priority queue. |
286 |
< |
* |
287 |
< |
* @param element the element to add. |
288 |
< |
* @return true |
289 |
< |
* @throws ClassCastException if the specified element cannot be compared |
290 |
< |
* with elements currently in the priority queue according |
291 |
< |
* to the priority queue's ordering. |
292 |
< |
* @throws NullPointerException if the specified element is null. |
489 |
> |
* Remove all elements from the priority queue. |
490 |
|
*/ |
491 |
< |
public boolean offer(E element) { |
295 |
< |
if (element == null) |
296 |
< |
throw new NullPointerException(); |
491 |
> |
public void clear() { |
492 |
|
modCount++; |
493 |
|
|
494 |
< |
// Grow backing store if necessary |
495 |
< |
if (++size == queue.length) { |
496 |
< |
E[] newQueue = new E[2 * queue.length]; |
302 |
< |
System.arraycopy(queue, 0, newQueue, 0, size); |
303 |
< |
queue = newQueue; |
304 |
< |
} |
494 |
> |
// Null out element references to prevent memory leak |
495 |
> |
for (int i=1; i<=size; i++) |
496 |
> |
queue[i] = null; |
497 |
|
|
498 |
< |
queue[size] = element; |
307 |
< |
fixUp(size); |
308 |
< |
return true; |
498 |
> |
size = 0; |
499 |
|
} |
500 |
|
|
501 |
|
/** |
502 |
< |
* Remove all elements from the priority queue. |
502 |
> |
* Removes and returns the first element from queue. |
503 |
|
*/ |
504 |
< |
public void clear() { |
504 |
> |
public E remove() { |
505 |
> |
if (size == 0) |
506 |
> |
throw new NoSuchElementException(); |
507 |
|
modCount++; |
508 |
|
|
509 |
< |
// Null out element references to prevent memory leak |
510 |
< |
for (int i=1; i<=size; i++) |
511 |
< |
queue[i] = null; |
509 |
> |
E result = (E) queue[1]; |
510 |
> |
queue[1] = queue[size]; |
511 |
> |
queue[size--] = null; // Drop extra ref to prevent memory leak |
512 |
> |
if (size > 1) |
513 |
> |
fixDown(1); |
514 |
|
|
515 |
< |
size = 0; |
515 |
> |
return result; |
516 |
|
} |
517 |
|
|
518 |
|
/** |
519 |
< |
* Removes and returns the ith element from queue. Recall |
520 |
< |
* that queue is one-based, so 1 <= i <= size. |
519 |
> |
* Removes and returns the ith element from queue. (Recall that queue |
520 |
> |
* is one-based, so 1 <= i <= size.) |
521 |
|
* |
522 |
< |
* XXX: Could further special-case i==size, but is it worth it? |
523 |
< |
* XXX: Could special-case i==0, but is it worth it? |
522 |
> |
* Normally this method leaves the elements at positions from 1 up to i-1, |
523 |
> |
* inclusive, untouched. Under these circumstances, it returns null. |
524 |
> |
* Occasionally, in order to maintain the heap invariant, it must move |
525 |
> |
* the last element of the list to some index in the range [2, i-1], |
526 |
> |
* and move the element previously at position (i/2) to position i. |
527 |
> |
* Under these circumstances, this method returns the element that was |
528 |
> |
* previously at the end of the list and is now at some position between |
529 |
> |
* 2 and i-1 inclusive. |
530 |
|
*/ |
531 |
< |
private E remove(int i) { |
532 |
< |
assert i <= size; |
531 |
> |
private E removeAt(int i) { |
532 |
> |
assert i > 0 && i <= size; |
533 |
|
modCount++; |
534 |
|
|
535 |
< |
E result = queue[i]; |
536 |
< |
queue[i] = queue[size]; |
535 |
> |
E moved = (E) queue[size]; |
536 |
> |
queue[i] = moved; |
537 |
|
queue[size--] = null; // Drop extra ref to prevent memory leak |
538 |
< |
if (i <= size) |
538 |
> |
if (i <= size) { |
539 |
|
fixDown(i); |
540 |
< |
return result; |
540 |
> |
if (queue[i] == moved) { |
541 |
> |
fixUp(i); |
542 |
> |
if (queue[i] != moved) |
543 |
> |
return moved; |
544 |
> |
} |
545 |
> |
} |
546 |
> |
return null; |
547 |
|
} |
548 |
|
|
549 |
|
/** |
559 |
|
if (comparator == null) { |
560 |
|
while (k > 1) { |
561 |
|
int j = k >> 1; |
562 |
< |
if (((Comparable)queue[j]).compareTo(queue[k]) <= 0) |
562 |
> |
if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 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 (k > 1) { |
569 |
< |
int j = k >> 1; |
570 |
< |
if (comparator.compare(queue[j], queue[k]) <= 0) |
569 |
> |
int j = k >>> 1; |
570 |
> |
if (comparator.compare((E)queue[j], (E)queue[k]) <= 0) |
571 |
|
break; |
572 |
< |
E tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
572 |
> |
Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
573 |
|
k = j; |
574 |
|
} |
575 |
|
} |
587 |
|
private void fixDown(int k) { |
588 |
|
int j; |
589 |
|
if (comparator == null) { |
590 |
< |
while ((j = k << 1) <= size) { |
591 |
< |
if (j<size && ((Comparable)queue[j]).compareTo(queue[j+1]) > 0) |
590 |
> |
while ((j = k << 1) <= size && (j > 0)) { |
591 |
> |
if (j<size && |
592 |
> |
((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0) |
593 |
|
j++; // j indexes smallest kid |
594 |
< |
if (((Comparable)queue[k]).compareTo(queue[j]) <= 0) |
594 |
> |
|
595 |
> |
if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0) |
596 |
|
break; |
597 |
< |
E tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
597 |
> |
Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
598 |
|
k = j; |
599 |
|
} |
600 |
|
} else { |
601 |
< |
while ((j = k << 1) <= size) { |
602 |
< |
if (j < size && comparator.compare(queue[j], queue[j+1]) > 0) |
601 |
> |
while ((j = k << 1) <= size && (j > 0)) { |
602 |
> |
if (j<size && |
603 |
> |
comparator.compare((E)queue[j], (E)queue[j+1]) > 0) |
604 |
|
j++; // j indexes smallest kid |
605 |
< |
if (comparator.compare(queue[k], queue[j]) <= 0) |
605 |
> |
if (comparator.compare((E)queue[k], (E)queue[j]) <= 0) |
606 |
|
break; |
607 |
< |
E tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
607 |
> |
Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp; |
608 |
|
k = j; |
609 |
|
} |
610 |
|
} |
611 |
|
} |
612 |
|
|
613 |
|
/** |
614 |
< |
* Returns the comparator associated with this priority queue, or |
615 |
< |
* <tt>null</tt> if it uses its elements' natural ordering. |
614 |
> |
* Establishes the heap invariant (described above) in the entire tree, |
615 |
> |
* assuming nothing about the order of the elements prior to the call. |
616 |
> |
*/ |
617 |
> |
private void heapify() { |
618 |
> |
for (int i = size/2; i >= 1; i--) |
619 |
> |
fixDown(i); |
620 |
> |
} |
621 |
> |
|
622 |
> |
/** |
623 |
> |
* Returns the comparator used to order this collection, or <tt>null</tt> |
624 |
> |
* if this collection is sorted according to its elements natural ordering |
625 |
> |
* (using <tt>Comparable</tt>). |
626 |
|
* |
627 |
< |
* @return the comparator associated with this priority queue, or |
628 |
< |
* <tt>null</tt> if it uses its elements' natural ordering. |
627 |
> |
* @return the comparator used to order this collection, or <tt>null</tt> |
628 |
> |
* if this collection is sorted according to its elements natural ordering. |
629 |
|
*/ |
630 |
< |
Comparator<E> comparator() { |
630 |
> |
public Comparator<? super E> comparator() { |
631 |
|
return comparator; |
632 |
|
} |
633 |
+ |
|
634 |
+ |
/** |
635 |
+ |
* Save the state of the instance to a stream (that |
636 |
+ |
* is, serialize it). |
637 |
+ |
* |
638 |
+ |
* @serialData The length of the array backing the instance is |
639 |
+ |
* emitted (int), followed by all of its elements (each an |
640 |
+ |
* <tt>Object</tt>) in the proper order. |
641 |
+ |
* @param s the stream |
642 |
+ |
*/ |
643 |
+ |
private void writeObject(java.io.ObjectOutputStream s) |
644 |
+ |
throws java.io.IOException{ |
645 |
+ |
// Write out element count, and any hidden stuff |
646 |
+ |
s.defaultWriteObject(); |
647 |
+ |
|
648 |
+ |
// Write out array length |
649 |
+ |
s.writeInt(queue.length); |
650 |
+ |
|
651 |
+ |
// Write out all elements in the proper order. |
652 |
+ |
for (int i=0; i<size; i++) |
653 |
+ |
s.writeObject(queue[i]); |
654 |
+ |
} |
655 |
+ |
|
656 |
+ |
/** |
657 |
+ |
* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is, |
658 |
+ |
* deserialize it). |
659 |
+ |
* @param s the stream |
660 |
+ |
*/ |
661 |
+ |
private void readObject(java.io.ObjectInputStream s) |
662 |
+ |
throws java.io.IOException, ClassNotFoundException { |
663 |
+ |
// Read in size, and any hidden stuff |
664 |
+ |
s.defaultReadObject(); |
665 |
+ |
|
666 |
+ |
// Read in array length and allocate array |
667 |
+ |
int arrayLength = s.readInt(); |
668 |
+ |
queue = new Object[arrayLength]; |
669 |
+ |
|
670 |
+ |
// Read in all elements in the proper order. |
671 |
+ |
for (int i=0; i<size; i++) |
672 |
+ |
queue[i] = (E) s.readObject(); |
673 |
+ |
} |
674 |
+ |
|
675 |
|
} |