Java OCA OCP Practice Question 1204

Question

Given the proper import statement(s) and

import java.util.PriorityQueue;

public class Main {
   public static void main(String[] args) {
      PriorityQueue<String> pq = new PriorityQueue<String>();
      pq.add("2");
      pq.add("4");
      System.out.print(pq.peek() + " ");
      pq.offer("1");
      pq.add("3");
      pq.remove("1");
      System.out.print(pq.poll() + " ");
      if (pq.remove("2"))
         System.out.print(pq.poll() + " ");
      System.out.println(pq.poll() + " " + pq.peek());
   }//from  w w  w  . ja va  2 s. c om
}

What is the result?

  • A. 2 2 3 3
  • B. 2 2 3 4
  • C. 4 3 3 4
  • D. 2 2 3 3 3
  • E. 4 3 3 3 3
  • F. 2 2 3 3 4
  • G. Compilation fails
  • H. An exception is thrown at runtime


B is correct.

Note

add() and offer() both add to in this case naturally sorted queues.

The calls to poll() both return and then remove the first item from the queue, so the test fails.




PreviousNext

Related