Quick revision
The short answer
java.util.PriorityQueue is a binary min-heap stored in an array, ordered by the elements' natural ordering or by a Comparator we supply. offer and poll cost O(log n), peek costs O(1), and remove(Object) and contains cost O(n) because they scan the array. Its iterator and toString walk the array in storage order, not priority order; only repeated poll returns elements by priority, and elements with equal priority come out in no guaranteed order.
What to remember
In this answer, we saw that PriorityQueue is a binary min-heap stored in an array, where index k has children at 2k + 1 and 2k + 2. offer sifts the new element up and poll moves the last element to the root and sifts it down, both O(log n), while peek is O(1) and contains and remove(Object) scan the array in O(n). The iterator and toString show storage order, not priority order. The queue is unbounded, rejects nulls, is not thread-safe (PriorityBlockingQueue is), and gives no order among equal elements unless we add a tie-breaker.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
java.util.PriorityQueue is a binary min-heap stored in an array, ordered by the elements' natural ordering or by a Comparator we supply. offer and poll cost O(log n), peek costs O(1), and remove(Object) and contains cost O(n) because they scan the array. Its iterator and toString walk the array in storage order, not priority order; only repeated poll returns elements by priority, and elements with equal priority come out in no guaranteed order.
Why this question is asked
PriorityQueue is the standard tool for always processing the most urgent item next: schedulers, top-k problems, Dijkstra's shortest path, event simulations. It is also a class whose behaviour surprises people, mostly because printing or iterating it seems to show the elements in a random order. Interviewers ask about its internals to see whether we understand heaps well enough to predict its costs and avoid its traps. In this answer, we will recap what a binary heap is, see how it is stored in an array, follow offer and poll step by step, list the cost of each operation and why, explain what the iterator returns, and finish with nulls, growth, thread safety and ties.
1A Quick Recap of Binary Heaps
A binary heap is a tree with two rules. First, it is complete: every level is full except possibly the last, which fills from the left. Second, it is ordered: in a min-heap, every parent is smaller than or equal to its children. The second rule means the smallest element is always at the root, but it says nothing about the order between siblings or between different branches.
That is exactly the trade-off a priority queue wants. We only ever need the smallest element quickly, so we keep just enough order to find it, and we do not pay to keep everything fully sorted. With a Comparator such as Comparator.reverseOrder(), the same structure becomes a max-heap, because smallest now means smallest according to the comparator.
2How the Heap Lives in an Array
Because the tree is complete, it needs no node objects or pointers. PriorityQueue stores it in a plain Object array called queue. The root is at index 0, and for an element at index k, its children are at 2k + 1 and 2k + 2 and its parent is at (k - 1) / 2. A new queue starts with capacity 11 and grows when full.
| Index | Element | Parent index | Children indexes |
|---|---|---|---|
| 0 | 1 (root, smallest) | none | 1 and 2 |
| 1 | 2 | 0 | 3 and 4 |
| 2 | 4 | 0 | 5 and 6 (empty) |
| 3 | 5 | 1 | none yet |
| 4 | 3 | 1 | none yet |
Notice that the printed order is not sorted. Index 0 holds 1, its children at 1 and 2 hold 2 and 4, and the children of index 1, at 3 and 4, hold 5 and 3. Every parent is smaller than its children, so the heap rule holds, but 5 comes before 3 in the array. That is all a heap promises.
3Following offer and poll Step by Step
offer places the new element in the first free slot at the end of the array, which keeps the tree complete, and then sifts it up: while the element is smaller than its parent, the two swap places. When we offered 2 above, it landed at index 3, compared with its parent 5 at index 1, swapped, then compared with 1 at the root and stopped. At most one comparison per level is needed, and a heap of n elements has about log2(n) levels, so offer is O(log n).
poll removes the root, which is the answer, and must fill the hole. It takes the last element of the array, puts it at the root and sifts it down: it compares the element with the smaller of its two children and swaps if the child is smaller, repeating until the element is no larger than its children. Again that is one step per level, so poll is O(log n). peek just reads index 0, so it is O(1).
- Take the root as the result1
- Move the last element to the root[3, 2, 4, 5]
- Is 3 larger than its smaller child (2)?YesSwap: [2, 3, 4, 5]NoStop
- Does 3 have a smaller child now?YesSwap againNoStop: heap rule holds
- Return 1about
log2(n)comparisons in total
5 steps in order. Play them, or step through them one at a time.
So repeated poll returns 1, 2, 3, 4, 5 in priority order, even though the array was never sorted. Each poll restores just enough order to make the next minimum sit at the root.
4Why remove(Object) and contains Are O(n)
The heap only knows where the smallest element is. To find an arbitrary element, it has no shortcut, so contains and remove(Object) scan the array from index 0 with equals until they find a match. That is O(n). remove(Object) then also has to repair the heap at that position, which adds O(log n), but the scan dominates.
This matters in practice. A scheduler that cancels jobs by calling queue.remove(job) on a queue of a million jobs does a million equals calls per cancellation. If cancellations are frequent, we need a different design, such as marking entries as cancelled and skipping them when they are polled.
5What the Iterator Returns
The iterator, toString, toArray and forEach all walk the internal array from index 0 to the end. They therefore return elements in storage order, which is heap order, not priority order. This is documented: the iterator is not guaranteed to traverse elements in any particular order. If we need the elements sorted without emptying the queue, we copy them and sort the copy, for example with Arrays.sort(pq.toArray()), or we poll from a copy of the queue.
The iterator is also fail-fast: if the queue is modified other than through the iterator during iteration, the next call throws ConcurrentModificationException. A stream over the queue has the same order as the iterator, so pq.stream().forEach(...) is not in priority order either.
6Nulls, Growth, Thread Safety and Ties
PriorityQueue rejects null with NullPointerException, because poll and peek use null to mean the queue is empty, and because null cannot be compared. It is unbounded: when the array is full it grows, roughly doubling while small and growing by half once larger, so offer never fails for lack of space until memory runs out. The constructor that takes a collection builds the heap in O(n) with a bottom-up heapify, which is faster than n separate offers.
It is not thread-safe. Two threads offering at the same time can corrupt the array and break the heap rule. PriorityBlockingQueue is the thread-safe version: it uses a single lock, and its take method blocks while the queue is empty. Finally, elements that compare as equal come out in no guaranteed order; the heap does not remember insertion order. If we need first-in-first-out among equal priorities, we add a sequence number as a tie-breaker in the comparator.
7Follow-up questions
How would you print a PriorityQueue in priority order without losing its contents?
Copy it and drain the copy: new PriorityQueue<>(pq) is built in O(n), and polling it n times gives priority order in O(n log n). Alternatively sort an array copy with toArray and Arrays.sort, passing the same comparator. The original queue stays untouched either way.
Why is building a heap from a collection O(n) and not O(n log n)?
Bottom-up heapify sifts down each internal node, starting from the last parent and moving to the root. Most nodes are near the bottom and sift down only a level or two, so the total work sums to a constant times n. Doing n separate offers can cost O(n log n).
When would you use a TreeSet instead?
When we need fast removal of arbitrary elements, ordered iteration or range queries. TreeSet gives O(log n) for add, remove and contains and iterates in sorted order. But it does not allow duplicates by comparator, so equal-priority items need a tie-breaker, and it uses a node per element, so it is heavier than the array heap.
8Conclusion
In this answer, we saw that PriorityQueue is a binary min-heap stored in an array, where index k has children at 2k + 1 and 2k + 2. offer sifts the new element up and poll moves the last element to the root and sifts it down, both O(log n), while peek is O(1) and contains and remove(Object) scan the array in O(n). The iterator and toString show storage order, not priority order. The queue is unbounded, rejects nulls, is not thread-safe (PriorityBlockingQueue is), and gives no order among equal elements unless we add a tie-breaker.
Open with
PriorityQueue is a binary min-heap stored in an array. The root at index zero is always the smallest element according to natural ordering or the Comparator we pass, and each element at index k has its children at 2k plus 1 and 2k plus 2. offer appends the element at the end and sifts it up, swapping with its parent while it is smaller, so it is O(log n). poll removes the root, moves the last element to the root and sifts it down by swapping with the smaller child, also O(log n). peek just reads index zero, so it is constant time. contains and remove of an arbitrary object have no shortcut and scan the array, so they are O(n), which matters if a scheduler cancels jobs that way.
Then, if they want more
A common surprise is that the iterator and toString walk the array in storage order, so printing the queue does not show priority order; only repeated poll gives elements in order. The queue is unbounded and grows as needed, rejects nulls because null means empty for poll and peek, and it is not thread-safe.
For concurrent use there is PriorityBlockingQueue, which is protected by a lock and blocks on take when empty. And elements with equal priority come out in no guaranteed order, so if I need FIFO among equals I add a sequence number to the comparator as a tie-breaker.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "How is java.util.PriorityQueue implemented, what are the costs of its main operations...": https://scrivio-interview-library.netlify.app/java/queues-and-deques/4526e9404b/