Java OCA OCP Practice Question 2398

Question

What is the output of the following code?

import java.util.*;
public class Main {
    public static void main (String [] args) {
        Set<Phone> set = new TreeSet<>();
        set.add(new Phone("Harry"));
         set.add(new Phone("Paul"));
         set.add(new Phone("Harry"));
         set.add(new Phone("Paul"));

         Iterator <Phone> iterator = set.iterator ();

         while (iterator.hasNext()) {
             Phone ph = iterator.next();
             switch (ph.toString()){
                 case "Harry": System.out.print("Harry ");
                         break;
                 case "Paul": System.out.print("<Paul> ");
                         break;
             }/*from w  ww . j a v a  2 s.c o  m*/
         }
         System.out.print("Set size=" + set.size());
     }
 }
 class Phone{
     String manufacturer;
     Phone(String value) {
         manufacturer = value;
     }
     public String toString() {
         return manufacturer;
     }
 }
  • a <Paul> Harry Harry <Paul> Set size=4
  • b <Paul> Harry <Paul> Harry Set size=4
  • c Harry Harry <Paul> <Paul> Set size=4
  • d <Paul> Harry Set size=2
  • e Harry <Paul> Set size=2
  • f Compilation error
  • g Runtime exception
  • h The output is unpredictable.


g

Note

The code fails at runtime with the following message because class Phone doesn't implement the java.lang.Comparable interface: Exception in thread "main" java.lang.ClassCastException: Phone can't be cast to java.lang.Comparable.

This exception is thrown when the code tries to add a value to set.

A TreeSet should be able to sort its elements either by using their natural order or by using a Comparator object passed to TreeSet's constructor.

A class defines its natural sort order by implementing the Comparable interface.

Class Phone doesn't define its natural order.

Also, while instantiating set, no Comparator object is passed to TreeSet's constructor.

You can instantiate a TreeSet that neither uses elements with a natural sort order nor is passed a Comparator object.

But such a TreeSet will throw a runtime exception when you try to add an element to it.




PreviousNext

Related