PriorityQueue only guarantees that peek/poll return the smallest element; iterating or printing it exposes the raw binary-heap array order, which is not sorted.
PriorityQueue<Integer> pq = new PriorityQueue<>(List.of(50, 10, 40, 20, 30));
System.out.println("toString (heap array order): " + pq);
StringBuilder polled = new StringBuilder();
while (!pq.isEmpty()) {
polled.append(pq.poll()).append(" ");
}
System.out.println("poll() order (sorted): " + polled.toString().trim());
toString (heap array order): [10, 20, 40, 50, 30]
poll() order (sorted): 10 20 30 40 50
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27