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);
- A. 13145
- B. 11345
- C. 54311
- 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
- A Printer interface declares print(), scan(), fax() and staple(). A cheap printer class must implement all four and throws…
- What is printed? java String a = "Hi"; String b = new String("Hi"); String c = b.intern(); StringBuilder d = new StringBuilder("Hi")…
- What is printed? java abstract class Shape { Shape() { System.out.print(area() + " "); } abstract double area(); } class Sq extends Shape…
- What is printed? java List<Integer> l = new ArrayList<>(List.of(5, 6, 7)); Iterator<Integer> it = l.iterator(); while (it.hasNext()) if…
- What does this Java program print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get()…
- What does this Java program print? class P { P() { init(); } void init() { System.out.print("P "); } } class C extends P { int x = 5; C()…