1. /*
  2. * @(#)PriorityQueue.java 1.6 04/06/11
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util;
  8. /**
  9. * An unbounded priority {@linkplain Queue queue} based on a priority
  10. * heap. This queue orders elements according to an order specified
  11. * at construction time, which is specified either according to their
  12. * <i>natural order</i> (see {@link Comparable}), or according to a
  13. * {@link java.util.Comparator}, depending on which constructor is
  14. * used. A priority queue does not permit <tt>null</tt> elements.
  15. * A priority queue relying on natural ordering also does not
  16. * permit insertion of non-comparable objects (doing so may result
  17. * in <tt>ClassCastException</tt>).
  18. *
  19. * <p>The <em>head</em> of this queue is the <em>least</em> element
  20. * with respect to the specified ordering. If multiple elements are
  21. * tied for least value, the head is one of those elements -- ties are
  22. * broken arbitrarily. The queue retrieval operations <tt>poll</tt>,
  23. * <tt>remove</tt>, <tt>peek</tt>, and <tt>element</tt> access the
  24. * element at the head of the queue.
  25. *
  26. * <p>A priority queue is unbounded, but has an internal
  27. * <i>capacity</i> governing the size of an array used to store the
  28. * elements on the queue. It is always at least as large as the queue
  29. * size. As elements are added to a priority queue, its capacity
  30. * grows automatically. The details of the growth policy are not
  31. * specified.
  32. *
  33. * <p>This class and its iterator implement all of the
  34. * <em>optional</em> methods of the {@link Collection} and {@link
  35. * Iterator} interfaces.
  36. * 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
  52. * <tt>remove(Object)</tt> and <tt>contains(Object)</tt> methods; and
  53. * constant time for the retrieval methods (<tt>peek</tt>,
  54. * <tt>element</tt>, and <tt>size</tt>).
  55. *
  56. * <p>This class is a member of the
  57. * <a href="{@docRoot}/../guide/collections/index.html">
  58. * Java Collections Framework</a>.
  59. * @since 1.5
  60. * @version 1.6, 06/11/04
  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 java.io.Serializable {
  66. private static final long serialVersionUID = -7720805057305804111L;
  67. private static final int DEFAULT_INITIAL_CAPACITY = 11;
  68. /**
  69. * Priority queue represented as a balanced binary heap: the two children
  70. * of queue[n] are queue[2*n] and queue[2*n + 1]. The priority queue is
  71. * ordered by comparator, or by the elements' natural ordering, if
  72. * comparator is null: For each node n in the heap and each descendant d
  73. * of n, n <= d.
  74. *
  75. * The element with the lowest value is in queue[1], assuming the queue is
  76. * nonempty. (A one-based array is used in preference to the traditional
  77. * zero-based array to simplify parent and child calculations.)
  78. *
  79. * queue.length must be >= 2, even if size == 0.
  80. */
  81. private transient Object[] queue;
  82. /**
  83. * The number of elements in the priority queue.
  84. */
  85. private int size = 0;
  86. /**
  87. * The comparator, or null if priority queue uses elements'
  88. * natural ordering.
  89. */
  90. private final Comparator<? super E> comparator;
  91. /**
  92. * The number of times this priority queue has been
  93. * <i>structurally modified</i>. See AbstractList for gory details.
  94. */
  95. private transient int modCount = 0;
  96. /**
  97. * Creates a <tt>PriorityQueue</tt> with the default initial capacity
  98. * (11) that orders its elements according to their natural
  99. * ordering (using <tt>Comparable</tt>).
  100. */
  101. public PriorityQueue() {
  102. this(DEFAULT_INITIAL_CAPACITY, null);
  103. }
  104. /**
  105. * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
  106. * that orders its elements according to their natural ordering
  107. * (using <tt>Comparable</tt>).
  108. *
  109. * @param initialCapacity the initial capacity for this priority queue.
  110. * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
  111. * than 1
  112. */
  113. public PriorityQueue(int initialCapacity) {
  114. this(initialCapacity, null);
  115. }
  116. /**
  117. * Creates a <tt>PriorityQueue</tt> with the specified initial capacity
  118. * that orders its elements according to the specified comparator.
  119. *
  120. * @param initialCapacity the initial capacity for this priority queue.
  121. * @param comparator the comparator used to order this priority queue.
  122. * If <tt>null</tt> then the order depends on the elements' natural
  123. * ordering.
  124. * @throws IllegalArgumentException if <tt>initialCapacity</tt> is less
  125. * than 1
  126. */
  127. public PriorityQueue(int initialCapacity,
  128. Comparator<? super E> comparator) {
  129. if (initialCapacity < 1)
  130. throw new IllegalArgumentException();
  131. this.queue = new Object[initialCapacity + 1];
  132. this.comparator = comparator;
  133. }
  134. /**
  135. * Common code to initialize underlying queue array across
  136. * constructors below.
  137. */
  138. private void initializeArray(Collection<? extends E> c) {
  139. int sz = c.size();
  140. int initialCapacity = (int)Math.min((sz * 110L) / 100,
  141. Integer.MAX_VALUE - 1);
  142. if (initialCapacity < 1)
  143. initialCapacity = 1;
  144. this.queue = new Object[initialCapacity + 1];
  145. }
  146. /**
  147. * Initially fill elements of the queue array under the
  148. * knowledge that it is sorted or is another PQ, in which
  149. * case we can just place the elements in the order presented.
  150. */
  151. private void fillFromSorted(Collection<? extends E> c) {
  152. for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
  153. queue[++size] = i.next();
  154. }
  155. /**
  156. * Initially fill elements of the queue array that is not to our knowledge
  157. * sorted, so we must rearrange the elements to guarantee the heap
  158. * invariant.
  159. */
  160. private void fillFromUnsorted(Collection<? extends E> c) {
  161. for (Iterator<? extends E> i = c.iterator(); i.hasNext(); )
  162. queue[++size] = i.next();
  163. heapify();
  164. }
  165. /**
  166. * Creates a <tt>PriorityQueue</tt> containing the elements in the
  167. * specified collection. The priority queue has an initial
  168. * capacity of 110% of the size of the specified collection or 1
  169. * if the collection is empty. If the specified collection is an
  170. * instance of a {@link java.util.SortedSet} or is another
  171. * <tt>PriorityQueue</tt>, the priority queue will be sorted
  172. * according to the same comparator, or according to its elements'
  173. * natural order if the collection is sorted according to its
  174. * elements' natural order. Otherwise, the priority queue is
  175. * ordered according to its elements' natural order.
  176. *
  177. * @param c the collection whose elements are to be placed
  178. * into this priority queue.
  179. * @throws ClassCastException if elements of the specified collection
  180. * cannot be compared to one another according to the priority
  181. * queue's ordering.
  182. * @throws NullPointerException if <tt>c</tt> or any element within it
  183. * is <tt>null</tt>
  184. */
  185. public PriorityQueue(Collection<? extends E> c) {
  186. initializeArray(c);
  187. if (c instanceof SortedSet) {
  188. SortedSet<? extends E> s = (SortedSet<? extends E>)c;
  189. comparator = (Comparator<? super E>)s.comparator();
  190. fillFromSorted(s);
  191. } else if (c instanceof PriorityQueue) {
  192. PriorityQueue<? extends E> s = (PriorityQueue<? extends E>) c;
  193. comparator = (Comparator<? super E>)s.comparator();
  194. fillFromSorted(s);
  195. } else {
  196. comparator = null;
  197. fillFromUnsorted(c);
  198. }
  199. }
  200. /**
  201. * Creates a <tt>PriorityQueue</tt> containing the elements in the
  202. * specified collection. The priority queue has an initial
  203. * capacity of 110% of the size of the specified collection or 1
  204. * if the collection is empty. This priority queue will be sorted
  205. * according to the same comparator as the given collection, or
  206. * according to its elements' natural order if the collection is
  207. * sorted according to its elements' natural order.
  208. *
  209. * @param c the collection whose elements are to be placed
  210. * into this priority queue.
  211. * @throws ClassCastException if elements of the specified collection
  212. * cannot be compared to one another according to the priority
  213. * queue's ordering.
  214. * @throws NullPointerException if <tt>c</tt> or any element within it
  215. * is <tt>null</tt>
  216. */
  217. public PriorityQueue(PriorityQueue<? extends E> c) {
  218. initializeArray(c);
  219. comparator = (Comparator<? super E>)c.comparator();
  220. fillFromSorted(c);
  221. }
  222. /**
  223. * Creates a <tt>PriorityQueue</tt> containing the elements in the
  224. * specified collection. The priority queue has an initial
  225. * capacity of 110% of the size of the specified collection or 1
  226. * if the collection is empty. This priority queue will be sorted
  227. * according to the same comparator as the given collection, or
  228. * according to its elements' natural order if the collection is
  229. * sorted according to its elements' natural order.
  230. *
  231. * @param c the collection whose elements are to be placed
  232. * into this priority queue.
  233. * @throws ClassCastException if elements of the specified collection
  234. * cannot be compared to one another according to the priority
  235. * queue's ordering.
  236. * @throws NullPointerException if <tt>c</tt> or any element within it
  237. * is <tt>null</tt>
  238. */
  239. public PriorityQueue(SortedSet<? extends E> c) {
  240. initializeArray(c);
  241. comparator = (Comparator<? super E>)c.comparator();
  242. fillFromSorted(c);
  243. }
  244. /**
  245. * Resize array, if necessary, to be able to hold given index
  246. */
  247. private void grow(int index) {
  248. int newlen = queue.length;
  249. if (index < newlen) // don't need to grow
  250. return;
  251. if (index == Integer.MAX_VALUE)
  252. throw new OutOfMemoryError();
  253. while (newlen <= index) {
  254. if (newlen >= Integer.MAX_VALUE / 2) // avoid overflow
  255. newlen = Integer.MAX_VALUE;
  256. else
  257. newlen <<= 2;
  258. }
  259. Object[] newQueue = new Object[newlen];
  260. System.arraycopy(queue, 0, newQueue, 0, queue.length);
  261. queue = newQueue;
  262. }
  263. /**
  264. * Inserts the specified element into this priority queue.
  265. *
  266. * @return <tt>true</tt>
  267. * @throws ClassCastException if the specified element cannot be compared
  268. * with elements currently in the priority queue according
  269. * to the priority queue's ordering.
  270. * @throws NullPointerException if the specified element is <tt>null</tt>.
  271. */
  272. public boolean offer(E o) {
  273. if (o == null)
  274. throw new NullPointerException();
  275. modCount++;
  276. ++size;
  277. // Grow backing store if necessary
  278. if (size >= queue.length)
  279. grow(size);
  280. queue[size] = o;
  281. fixUp(size);
  282. return true;
  283. }
  284. public E peek() {
  285. if (size == 0)
  286. return null;
  287. return (E) queue[1];
  288. }
  289. // Collection Methods - the first two override to update docs
  290. /**
  291. * Adds the specified element to this queue.
  292. * @return <tt>true</tt> (as per the general contract of
  293. * <tt>Collection.add</tt>).
  294. *
  295. * @throws NullPointerException if the specified element is <tt>null</tt>.
  296. * @throws ClassCastException if the specified element cannot be compared
  297. * with elements currently in the priority queue according
  298. * to the priority queue's ordering.
  299. */
  300. public boolean add(E o) {
  301. return offer(o);
  302. }
  303. /**
  304. * Removes a single instance of the specified element from this
  305. * queue, if it is present.
  306. */
  307. public boolean remove(Object o) {
  308. if (o == null)
  309. return false;
  310. if (comparator == null) {
  311. for (int i = 1; i <= size; i++) {
  312. if (((Comparable<E>)queue[i]).compareTo((E)o) == 0) {
  313. removeAt(i);
  314. return true;
  315. }
  316. }
  317. } else {
  318. for (int i = 1; i <= size; i++) {
  319. if (comparator.compare((E)queue[i], (E)o) == 0) {
  320. removeAt(i);
  321. return true;
  322. }
  323. }
  324. }
  325. return false;
  326. }
  327. /**
  328. * Returns an iterator over the elements in this queue. The iterator
  329. * does not return the elements in any particular order.
  330. *
  331. * @return an iterator over the elements in this queue.
  332. */
  333. public Iterator<E> iterator() {
  334. return new Itr();
  335. }
  336. private class Itr implements Iterator<E> {
  337. /**
  338. * Index (into queue array) of element to be returned by
  339. * subsequent call to next.
  340. */
  341. private int cursor = 1;
  342. /**
  343. * Index of element returned by most recent call to next,
  344. * unless that element came from the forgetMeNot list.
  345. * Reset to 0 if element is deleted by a call to remove.
  346. */
  347. private int lastRet = 0;
  348. /**
  349. * The modCount value that the iterator believes that the backing
  350. * List should have. If this expectation is violated, the iterator
  351. * has detected concurrent modification.
  352. */
  353. private int expectedModCount = modCount;
  354. /**
  355. * A list of elements that were moved from the unvisited portion of
  356. * the heap into the visited portion as a result of "unlucky" element
  357. * removals during the iteration. (Unlucky element removals are those
  358. * that require a fixup instead of a fixdown.) We must visit all of
  359. * the elements in this list to complete the iteration. We do this
  360. * after we've completed the "normal" iteration.
  361. *
  362. * We expect that most iterations, even those involving removals,
  363. * will not use need to store elements in this field.
  364. */
  365. private ArrayList<E> forgetMeNot = null;
  366. /**
  367. * Element returned by the most recent call to next iff that
  368. * element was drawn from the forgetMeNot list.
  369. */
  370. private Object lastRetElt = null;
  371. public boolean hasNext() {
  372. return cursor <= size || forgetMeNot != null;
  373. }
  374. public E next() {
  375. checkForComodification();
  376. E result;
  377. if (cursor <= size) {
  378. result = (E) queue[cursor];
  379. lastRet = cursor++;
  380. }
  381. else if (forgetMeNot == null)
  382. throw new NoSuchElementException();
  383. else {
  384. int remaining = forgetMeNot.size();
  385. result = forgetMeNot.remove(remaining - 1);
  386. if (remaining == 1)
  387. forgetMeNot = null;
  388. lastRet = 0;
  389. lastRetElt = result;
  390. }
  391. return result;
  392. }
  393. public void remove() {
  394. checkForComodification();
  395. if (lastRet != 0) {
  396. E moved = PriorityQueue.this.removeAt(lastRet);
  397. lastRet = 0;
  398. if (moved == null) {
  399. cursor--;
  400. } else {
  401. if (forgetMeNot == null)
  402. forgetMeNot = new ArrayList<E>();
  403. forgetMeNot.add(moved);
  404. }
  405. } else if (lastRetElt != null) {
  406. PriorityQueue.this.remove(lastRetElt);
  407. lastRetElt = null;
  408. } else {
  409. throw new IllegalStateException();
  410. }
  411. expectedModCount = modCount;
  412. }
  413. final void checkForComodification() {
  414. if (modCount != expectedModCount)
  415. throw new ConcurrentModificationException();
  416. }
  417. }
  418. public int size() {
  419. return size;
  420. }
  421. /**
  422. * Removes all elements from the priority queue.
  423. * The queue will be empty after this call returns.
  424. */
  425. public void clear() {
  426. modCount++;
  427. // Null out element references to prevent memory leak
  428. for (int i=1; i<=size; i++)
  429. queue[i] = null;
  430. size = 0;
  431. }
  432. public E poll() {
  433. if (size == 0)
  434. return null;
  435. modCount++;
  436. E result = (E) queue[1];
  437. queue[1] = queue[size];
  438. queue[size--] = null; // Drop extra ref to prevent memory leak
  439. if (size > 1)
  440. fixDown(1);
  441. return result;
  442. }
  443. /**
  444. * Removes and returns the ith element from queue. (Recall that queue
  445. * is one-based, so 1 <= i <= size.)
  446. *
  447. * Normally this method leaves the elements at positions from 1 up to i-1,
  448. * inclusive, untouched. Under these circumstances, it returns null.
  449. * Occasionally, in order to maintain the heap invariant, it must move
  450. * the last element of the list to some index in the range [2, i-1],
  451. * and move the element previously at position (i/2) to position i.
  452. * Under these circumstances, this method returns the element that was
  453. * previously at the end of the list and is now at some position between
  454. * 2 and i-1 inclusive.
  455. */
  456. private E removeAt(int i) {
  457. assert i > 0 && i <= size;
  458. modCount++;
  459. E moved = (E) queue[size];
  460. queue[i] = moved;
  461. queue[size--] = null; // Drop extra ref to prevent memory leak
  462. if (i <= size) {
  463. fixDown(i);
  464. if (queue[i] == moved) {
  465. fixUp(i);
  466. if (queue[i] != moved)
  467. return moved;
  468. }
  469. }
  470. return null;
  471. }
  472. /**
  473. * Establishes the heap invariant (described above) assuming the heap
  474. * satisfies the invariant except possibly for the leaf-node indexed by k
  475. * (which may have a nextExecutionTime less than its parent's).
  476. *
  477. * This method functions by "promoting" queue[k] up the hierarchy
  478. * (by swapping it with its parent) repeatedly until queue[k]
  479. * is greater than or equal to its parent.
  480. */
  481. private void fixUp(int k) {
  482. if (comparator == null) {
  483. while (k > 1) {
  484. int j = k >> 1;
  485. if (((Comparable<E>)queue[j]).compareTo((E)queue[k]) <= 0)
  486. break;
  487. Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
  488. k = j;
  489. }
  490. } else {
  491. while (k > 1) {
  492. int j = k >>> 1;
  493. if (comparator.compare((E)queue[j], (E)queue[k]) <= 0)
  494. break;
  495. Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
  496. k = j;
  497. }
  498. }
  499. }
  500. /**
  501. * Establishes the heap invariant (described above) in the subtree
  502. * rooted at k, which is assumed to satisfy the heap invariant except
  503. * possibly for node k itself (which may be greater than its children).
  504. *
  505. * This method functions by "demoting" queue[k] down the hierarchy
  506. * (by swapping it with its smaller child) repeatedly until queue[k]
  507. * is less than or equal to its children.
  508. */
  509. private void fixDown(int k) {
  510. int j;
  511. if (comparator == null) {
  512. while ((j = k << 1) <= size && (j > 0)) {
  513. if (j<size &&
  514. ((Comparable<E>)queue[j]).compareTo((E)queue[j+1]) > 0)
  515. j++; // j indexes smallest kid
  516. if (((Comparable<E>)queue[k]).compareTo((E)queue[j]) <= 0)
  517. break;
  518. Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
  519. k = j;
  520. }
  521. } else {
  522. while ((j = k << 1) <= size && (j > 0)) {
  523. if (j<size &&
  524. comparator.compare((E)queue[j], (E)queue[j+1]) > 0)
  525. j++; // j indexes smallest kid
  526. if (comparator.compare((E)queue[k], (E)queue[j]) <= 0)
  527. break;
  528. Object tmp = queue[j]; queue[j] = queue[k]; queue[k] = tmp;
  529. k = j;
  530. }
  531. }
  532. }
  533. /**
  534. * Establishes the heap invariant (described above) in the entire tree,
  535. * assuming nothing about the order of the elements prior to the call.
  536. */
  537. private void heapify() {
  538. for (int i = size2; i >= 1; i--)
  539. fixDown(i);
  540. }
  541. /**
  542. * Returns the comparator used to order this collection, or <tt>null</tt>
  543. * if this collection is sorted according to its elements natural ordering
  544. * (using <tt>Comparable</tt>).
  545. *
  546. * @return the comparator used to order this collection, or <tt>null</tt>
  547. * if this collection is sorted according to its elements natural ordering.
  548. */
  549. public Comparator<? super E> comparator() {
  550. return comparator;
  551. }
  552. /**
  553. * Save the state of the instance to a stream (that
  554. * is, serialize it).
  555. *
  556. * @serialData The length of the array backing the instance is
  557. * emitted (int), followed by all of its elements (each an
  558. * <tt>Object</tt>) in the proper order.
  559. * @param s the stream
  560. */
  561. private void writeObject(java.io.ObjectOutputStream s)
  562. throws java.io.IOException{
  563. // Write out element count, and any hidden stuff
  564. s.defaultWriteObject();
  565. // Write out array length
  566. s.writeInt(queue.length);
  567. // Write out all elements in the proper order.
  568. for (int i=1; i<=size; i++)
  569. s.writeObject(queue[i]);
  570. }
  571. /**
  572. * Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
  573. * deserialize it).
  574. * @param s the stream
  575. */
  576. private void readObject(java.io.ObjectInputStream s)
  577. throws java.io.IOException, ClassNotFoundException {
  578. // Read in size, and any hidden stuff
  579. s.defaultReadObject();
  580. // Read in array length and allocate array
  581. int arrayLength = s.readInt();
  582. queue = new Object[arrayLength];
  583. // Read in all elements in the proper order.
  584. for (int i=1; i<=size; i++)
  585. queue[i] = (E) s.readObject();
  586. }
  587. }