Java OCA OCP Practice Question 2708

Question

Given:

1. import java.util.*;  
2. public class Main {  
3.   public static void main(String[] args) {  
4.      PriorityQueue toDo = new PriorityQueue();  
5.      toDo.add("dishes");  
6.      toDo.add("laundry");  
7.      toDo.add("bills");  
8.      toDo.offer("bills");  
9.      System.out.print(toDo.size() + " " + toDo.poll());  
10.     System.out.print(" " + toDo.peek() + " " + toDo.poll());  
11.     System.out.println(" " + toDo.poll() + " " + toDo.poll());  
12.  }//from  w  ww. j  a va2s  .co m
13. } 

What is the result?

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


E is correct.

Note

The add() and offer() methods have the same functionality, and it's okay for PriorityQueue to have duplicate elements.

Remembering that PriorityQueue are sorted, the poll() method removes the first element in the queue and returns it.

The peek() method returns the first element from the queue but does NOT remove it.




PreviousNext

Related