Either Employee
has to implement Comparable
, or you need to provide a comparator when creating the TreeSet
.
This is spelled out in the documentation for SortedSet
:
All elements inserted into a sorted set must implement the
Comparable
interface (or be accepted by the specified comparator). Furthermore, all such elements must be mutually comparable:e1.compareTo(e2)
(orcomparator.compare(e1, e2)
) must not throw aClassCastException
for any elementse1
ande2
in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw aClassCastException
.
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.