📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!

  • google app store apple app store
  • ✖

      Question

      Consider the following Java code snippet:    

      import java.util.PriorityQueue;     public class HeapQuestion8 {         public static void main(String[] args) {             PriorityQueue pq = new PriorityQueue();             pq.add(5);             pq.add(1);             pq.add(5); // Adding a duplicate             pq.add(3);             System.out.println(pq.poll());             System.out.println(pq.poll());             System.out.println(pq.poll());         }     }     What will be the output of this program?
      A 1, 3, 5 Correct Answer Incorrect Answer
      B 1, 5, 5 Correct Answer Incorrect Answer
      C 3, 5, 5 Correct Answer Incorrect Answer
      D 1, 5, 3 Correct Answer Incorrect Answer
      E 5, 5, 3 Correct Answer Incorrect Answer

      Solution

      A PriorityQueue (min-heap by default for Integers) correctly handles duplicate elements. They are treated like any other element based on their priority.     1.  pq.add(5); pq.add(1); pq.add(5); pq.add(3);         The elements in the heap are {1, 3, 5, 5} (conceptually, 1 is at the root).     2.  System.out.println(pq.poll());         Removes and prints the smallest element: 1. The heap now contains {3, 5, 5}.     3.  System.out.println(pq.poll());         Removes and prints the next smallest element: 3. The heap now contains {5, 5}.     4.  System.out.println(pq.poll());         Removes and prints the next smallest element: 5. The heap now contains {5}.     Therefore, the output is 1, 3, 5.

      Practice Next
      ask-question