Java Reference
In-Depth Information
@Override
public String toString()
{
return name;
}
}
When you run this application, it generates the following output:
Exception in thread "main" java.lang.ClassCastException:
Employee cannot be cast to
java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1188)
at java.util.TreeMap.put(TreeMap.java:531)
at java.util.TreeSet.add(TreeSet.java:255)
at CustomClassAndSor-
tedSet.main(CustomClassAndSortedSet.java:9)
The ClassCastException instanceisthrownduringthesecond add() method
call because the sorted set implementation, an instance of TreeSet , is unable to call
the second Employee element's compareTo() method, because Employee does
not implement Comparable .
Thesolutiontothisproblemistohavetheclassimplement Comparable ,whichis
exactly what is revealed in Listing 5-11 .
Listing 5-11. Making Employee elements comparable
import java.util.SortedSet;
import java.util.TreeSet;
class CustomClassAndSortedSet
{
public static void main(String[] args)
{
SortedSet<Employee> sse = new TreeSet<>();
sse.add(new Employee("sally doe"));
sse.add(new Employee("bob doe"));
Employee e1 = new Employee("john doe");
Employee e2 = new Employee("john doe");
 
Search WWH ::




Custom Search