Java OCA OCP Practice Question 3167

Question

Which loop, when inserted independently at (1), will guarantee that the program will print sea|sells|she|shells|?

import static java.lang.System.out;

import java.util.Collections;
import java.util.PriorityQueue;

public class Main {
  public static void main(String[] args) {
    PriorityQueue<String> strPQ = new PriorityQueue<String>();
    Collections.addAll(strPQ, "shells", "she", "sells", "sea");
    // (1) INSERT LOOP HERE
    out.println();//from   w w  w .ja va  2s .  co  m
  }
}

Select the one correct answer.

(a)  for (String word : strPQ) {
       out.print(word + "|");
     }/*from www . ja  v a  2 s . c  o m*/
(b) for (String word : strPQ) {
      out.print(strPQ.peek() + "|");
    }

(c) while (strPQ.peek() != null) {
      out.print(strPQ.poll() + "|");
    }

(d) for (String word : strPQ) {
      out.print(strPQ.poll() + "|");
    }


(c)

Note

(a) uses an iterator which does not guarantee the order of traversal.

(b) traverses the queue, but only peeks at the (same) head element each time.

(d) uses an iterator, but tries to change the queue structurally by calling the poll() method at the same time, resulting in a java.util.ConcurrentModificationException.

Polling in (c) is done according to the priority ordering, which in this case is natural ordering for strings.




PreviousNext

Related