Comparable vs. Equals

Agylen: Comparable vs equals has a nice discussion of how compareTo is used in Sets.

If you don’t understand how Java is going to use your compareTo and your equals methods you can run into a problem with Sets. Basically you shouldn’t have a compareTo() method that returns 0 unless equals() returns true.

Since a Set only allows once instance of each object, it will ignore the addition of any objects it already contains. If your object implements the Comparator interface the Set will check the compareTo method not the equals method.

It is common to write compareTo methods that only look at one field. For example, you might want to sort Person objects by their last name and then first name. If you only check the last and first name field, then comparing two John Smiths would return 0 even if they were different objects. This would cause the Set to evaluate them as the same object and prevent you from adding the second John Smith to the Set.


Leave a Reply

Your email address will not be published. Required fields are marked *