Card 05/ 08
All 8 cards
GotchaDifficulty: Advanced1 min
Why Printing a PriorityQueue Does Not Show Poll Order
A test asserts on the contents of a priority queue, passes for six elements and fails for seven. Printing the queue shows the elements out of order, and polling them gives them back in order.
Queue<Integer> q = new PriorityQueue<>(List.of(5, 1, 4, 2, 8, 3, 7));
System.out.println(q);
while (!q.isEmpty()) { System.out.print(q.poll() + " "); }[1, 2, 3, 5, 8, 4, 7]
1 2 3 4 5 7 8A PriorityQueue is a heap, not a sorted list. A heap keeps one guarantee — the smallest element is at the front — and does not keep the rest in order, because maintaining full order would cost more than the guarantee is worth.
toString, iterator and the enhanced for all walk the underlying array in storage order, so they show the heap's shape rather than the order things will come out.
Poll to see the order, or copy into something sorted when you need to look. Never assert on the iteration order of a priority queue.
List<Integer> inOrder = new ArrayList<>();
while (!q.isEmpty()) { inOrder.add(q.poll()); }