Java Reference
In-Depth Information
(resultingfromthe equals() comparison)alsoshowsthatthesortedset'snaturalor-
dering is inconsistent with equals() , which violates SortedSet 's contract:
The ordering maintained by a sorted set (whether or not an explicit comparator is
provided) must be consistent with equals() if the sorted set is to correctly imple-
ment the Set interface. This is so because the Set interface is defined in terms of
the equals() operation, but a sorted set performs all element comparisons using its
compareTo() (or compare() ) method, so two elements that are deemed equal by
this method are, from the standpoint of the sorted set, equal.
Becausetheapplicationworkscorrectly,whyshould SortedSet 'scontractmatter?
Although the contract does not appear to matter with respect to the TreeSet imple-
mentation of SortedSet , perhaps it will matter in the context of a third-party class
that implements this interface.
Listing5-12showsyouhowtocorrectthisproblemandmake Employee instances
work with any implementation of a sorted set.
Listing 5-12. A contract-compliant Employee class
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");
sse.add(e1);
sse.add(e2);
System.out.println(sse);
System.out.println(e1.equals(e2));
}
}
class Employee implements Comparable<Employee>
{
 
Search WWH ::




Custom Search