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


    Question

    Consider the following Java code snippet:    

    import java.util.Collections;     import java.util.PriorityQueue;     public class HeapQuestion2 {         public static void main(String[] args) {             PriorityQueue maxHeap = new PriorityQueue(Collections.reverseOrder());             maxHeap.add(10);             maxHeap.add(5);             maxHeap.add(20);             maxHeap.add(3);             System.out.println(maxHeap.poll());             System.out.println(maxHeap.poll());         }     }     What will be the output of this program?
    A 3, 5 Correct Answer Incorrect Answer
    B 20, 10 Correct Answer Incorrect Answer
    C 10, 5 Correct Answer Incorrect Answer
    D 20, 3 Correct Answer Incorrect Answer
    E 5, 10 Correct Answer Incorrect Answer

    Solution

    By passing Collections.reverseOrder() to the PriorityQueue constructor, we create a max-heap, where the largest element has the highest priority (is at the root).     1.  maxHeap.add(10); maxHeap.add(5); maxHeap.add(20); maxHeap.add(3);         After these additions, the heap contains {20, 10, 5, 3} (conceptually, 20 is at the root).     2.  System.out.println(maxHeap.poll());         poll() removes and returns the largest element. So, 20 is removed and printed. The heap now contains {10, 5, 3}.     3.  System.out.println(maxHeap.poll());         poll() removes and returns the largest element again. So, 10 is removed and printed. The heap now contains {5, 3}.     Therefore, the output is 20, 10.

    Practice Next
    ask-question