ProgrammingModerateAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
pq.addAll(List.of(3, 1, 4, 1, 5));
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) sb.append(pq.poll());
System.out.print(sb);
  1. A. 13145
  2. B. 11345
  3. C. 54311
  4. D. 54131

Correct answer: C. 54311

With a reverse-order comparator the head is always the largest remaining element, so polling until empty yields 5, 4, 3, 1, 1. Iterating over the queue (not polling) would not give sorted order.

More OOP with C++ and Java questions

Exams that ask this topic