Java Reference
In-Depth Information
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
at java.util.TreeMap.put(
at java.util.TreeSet.add(
at CustomClassAndSor-
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