Java OCA OCP Practice Question 3169

Question

Which statements are true about the following program?

import java.util.Collection;
import java.util.Collections;
import java.util.NavigableSet;
import java.util.TreeSet;
public class Main {
  public static void main(String[] args) {
    NavigableSet<Integer> navSet
                          = new TreeSet<Integer>(Collections.reverseOrder());
    Collections.addAll(navSet, 2010, 3001, 2001);

    NavigableSet<Integer> ss1 = new TreeSet<Integer>(navSet);
    NavigableSet<Integer> ss2 = new TreeSet<Integer>((Collection<Integer>)navSet);

    for (Integer iRef : navSet)                                     // (1)
      System.out.print(iRef + "|");
    System.out.println();/*from  www .  j a v a 2s.  c  o m*/
    for (Integer iRef : ss1)                                        // (2)
      System.out.print(iRef + "|");
    System.out.println();
    for (Integer iRef : ss2)                                        // (3)
      System.out.print(iRef + "|");
    System.out.println();
    while (!ss1.isEmpty())                                          // (4)
      System.out.print(ss1.pollFirst() + "|");
    System.out.println();
    while (!ss2.isEmpty())                                          // (5)
      System.out.print(ss2.pollFirst() + "|");
  }
}

Select the three correct answers.

  • (a) The loop at (1) prints 3001|2010|2001|.
  • (b) The loops at (1), (2) and (4) print the same output.
  • (c) The loop at (3) prints 3001|2010|2001|.
  • (d) All the loops print the same output.
  • (e) The loops at (3) and (5) print the same output.


(a), (b), and (e)

Note

The output from the program is shown below.

3001|2010|2001|
3001|2010|2001|
2001|2010|3001|
3001|2010|2001|
2001|2010|3001|

First, the elements in the set navSet are ordered in reverse natural ordering.

In the statement

NavigableSet<Integer> ss1 = new TreeSet<Integer>(navSet);

the signature of the constructor called is

TreeSet<Integer>(SortedSet<E> set)

resulting in the same ordering for the elements in the set ss1 as in the set navSet, i.e., reverse natural ordering. In the statement

NavigableSet<Integer> ss2 = new TreeSet<Integer>((Collection<Integer>)navSet);

the signature of the constructor called is

TreeSet<Integer>(Collection<? extends E> collection)

resulting in the elements in set ss2 having the same natural ordering as in the set navSet.




PreviousNext

Related