📢 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.PriorityQueue;     class CustomObject {         int id;         String name;         public CustomObject(int id, String name) {             this.id = id;             this.name = name;         }     }     public class HeapQuestion6 {         public static void main(String[] args) {             PriorityQueue pq = new PriorityQueue();             pq.add(new CustomObject(1, "Alice"));             pq.add(new CustomObject(2, "Bob"));             System.out.println(pq.poll().name);         }     }     What will be the result of compiling and running this program?
    A It will compile and print "Alice". Correct Answer Incorrect Answer
    B It will compile and print "Bob". Correct Answer Incorrect Answer
    C It will compile but throw a ClassCastException at runtime. Correct Answer Incorrect Answer
    D It will result in a compilation error because CustomObject does not implement Comparable. Correct Answer Incorrect Answer
    E It will compile and print the object's hash code. Correct Answer Incorrect Answer

    Solution

    A PriorityQueue needs to know how to order its elements. For custom objects, there are two ways:     1.  The custom class implements the Comparable interface, defining its natural ordering.     2.  A Comparator is provided to the PriorityQueue constructor.     In this code, CustomObject does not implement Comparable, and no Comparator is provided. The Java compiler does not enforce this at compile time for PriorityQueue (it's a generic type parameter E extends Comparable or a Comparator is needed). However, when the PriorityQueue attempts to compare two CustomObject instances (e.g., during add() operations to maintain the heap property), it will try to cast them to Comparable, which will fail, resulting in a java.lang.ClassCastException at runtime.

    Practice Next
    ask-question