I am trying to add two 'Employee' objects to a TreeSet:
Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));
But it throws a ClassCastException:
Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable
at java.util.TreeMap.put(TreeMap.java:542)
at java.util.TreeSet.add(TreeSet.java:238)
at MyClient.main(MyClient.java:9)
But if I add only one object to the TreeSet:
Set<Employee> s = new TreeSet<Employee>();
s.add(new Employee(1001));
Or if I use a HashSet instead:
Set<Employee> s = new HashSet<Employee>();
s.add(new Employee(1001));
s.add(new Employee(1002));
Then it is successful. Why does the exception happen and how do I fix it?
From TreeSet#add(E) JavaDoc:
Basically what you need is to let
Employee
implementComparable
or provide aComparator
to theTreeSet
object.If you check
TreeMap
code you will see that if the comparator wasn't found within theMap
object, it will try to cast the key (yourEmployee
object) directly toComparator
:TreeSet
is an implementation ofSortedSet
. You can either letEmployee
implement theComparable
interface or provide an appropriateComparator
for yourTreeSet
:Either
Employee
has to implementComparable
, or you need to provide a comparator when creating theTreeSet
.This is spelled out in the documentation for
SortedSet
:If you don't fulfil these requirements, the sorted set won't know how to compare its elements and won't be able to function.
TreeSet
requires elements to implement theComparable
interface if a customComparator
is not set.HashSet
uses theequals
/hashCode
contract instead.You can add only one element into
TreeSet
which does not implementComparable
because it does not need to be compared with other elements.Take a look at the
TreeMap.put(K key, V value)
source code and you'll clearly see the reasons behind all your questions (TreeSet
is based onTreeMap
, hence the source reference).So implement Comparable interface to Employee object as it`s needed when you are using TreeSet, because TreeSet wants to keep elements sorted.