Java OCA OCP Practice Question 2626

Question

Consider the following program:

import java.util.*;

class Task implements Comparable<Task> {
        int priority;
        public Task(int val) {
                priority = val;
        }/*  w  w  w .ja va 2  s . c  o  m*/
public int compareTo(Task that) {
        if(this.priority == that.priority)
                return 0;
        else if (this.priority > that.priority)
                return -1;
        else
                return 1;
}
public String toString() {
        return new Integer(priority).toString();
}
}

class Main {
        public static void main(String []args) {
                PriorityQueue<Task> tasks = new PriorityQueue<Task>();
                tasks.add(new Task(10));
                tasks.add(new Task(15));
                tasks.add(new Task(5));
                Task task;
                while ( (task = tasks.poll()) != null) {
                        System.out.print(task + " ");
                }
        }
}

When executed, this program prints the following:

  • a) 10 10 10
  • b) 10 15 5
  • c) 5 10 15
  • d) 15 10 5
  • e) 5 5 5


d)

Note

The Task class implements Comparable<Task>, which specifies how to compare its elements.

The PriorityQueue method prioritizes the elements in the queue by calling the compareTo() method.

The compareTo() method returns -1 if the priority of the current Task object is greater than the priority of the compared Task object.

Hence the elements of the PriorityQueue are retrieved in the descending order.




PreviousNext

Related