Hi, As per the contract of compareTo method, it is a "natural comparison method". This means that this method should be used only to compare objects for order, and not to check equality of two objects.
Then, why do Set use compareTo method, instead of equals method, to eliminate duplicate items. It expects compareTo() to be consistent with equals. Isn't a breach of contract of compareTo method?
I'm not sure that it does use compareTo() for this purpose, although that will surely depend on what implementation of the Set interface you use. I can't imagine why a non-sorted collection (such as Set) would need to use the compareTo() method of it's objects. Indeed, it's contents will not necessarily implement the Comparable interface, hance the ClassCastException if you attempt to insert two objects that are not mutually comparable into a SortedSet, for example.
If you use a hash-based implementation, e.g. HashSet, I think (but have not checked / tested) that it probably uses equals() on the hashed bucket found from using hashCode(). If you have overridden equals() but not hashCode() there is a problem that the lookup method will be checking in the wrong hash bucket for your value. This is the reason for the Object.hashCode() contract that you must always override hashCode() when you override equals().
I think that the reason for using the hash code in these implementations is performance, and that you could logically use only the equals() method for a Set implementation - probably functionally OK but may have performance problems (of the same sort as if you choose a dumb implementation of hashCode() - e.g. always returns the same result for all objects of a given type which satisfies the contract but defeats the point). [ September 25, 2006: Message edited by: Simon Baker ]