Question
Consider the following Java code snippet:   import java.util.PriorityQueue;   import java.util.Comparator;   class Item {     int priority;     String name;     public Item(int priority, String name) {       this.priority = priority;       this.name = name;     }     @Override     public String toString() {       return name + "(" + priority + ")";     }   }   public class HeapQuestion7 {     public static void main(String[] args) {       // Create a min-heap based on 'priority'       PriorityQueue pq = new PriorityQueue(Comparator.comparingInt(item -> item.priority));       pq.add(new Item(5, "Task A"));       pq.add(new Item(1, "Task B"));       pq.add(new Item(10, "Task C"));       pq.add(new Item(3, "Task D"));       System.out.println(pq.poll().name);       System.out.println(pq.poll().name);     }   }   What will be the output of this program?
Solution
The PriorityQueue is initialized with a Comparator that orders Item objects based on their priority field in ascending order (min-heap behavior for priority).   1. pq.add(new Item(5, "Task A"));   2. pq.add(new Item(1, "Task B"));   3. pq.add(new Item(10, "Task C"));   4. pq.add(new Item(3, "Task D"));     After these additions, the item with the lowest priority value will be at the head of the queue. The priorities are 1, 3, 5, 10.   5. System.out.println(pq.poll().name);     The item with priority 1 ("Task B") is removed and its name is printed.   6. System.out.println(pq.poll().name);     The next item with the lowest priority (from the remaining items) is the one with priority 3 ("Task D"). It is removed and its name is printed.   Therefore, the output is Task B, Task D.
- Dynamic Programming is typically used for problems that exhibit which two main properties?
- Which algorithm is a greedy algorithm used to find the Minimum Spanning Tree (MST) of a graph by repeatedly adding the smallest weight edge that connects t...
- Which of the following best describes an accumulator in a CPU?
- What is the primary characteristic of the Spiral Model in software development?
- What is the difference between 'preemptive' and 'non-preemptive' scheduling?
- Which of the following statements accurately describes the use of the SQL CREATE statement?
- In open addressing, if a collision occurs and the hash function h(key) maps to an occupied slot, which probing technique attempts to find the next availabl...
- Which keyword is used in Java to indicate that a class is inheriting from another class?
- The output of circuit shown below is
- Which module in Python is used to define Abstract Base Classes (ABCs)?