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; } }
g
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.