posted 18 years ago
There are three methods that are closely related, each may be used by different Collection type to determine equality.
equals
hashCode
compareTo (For Sorted Collection, you must implement the Comparable innerface)
For your object to function in the various Collections as documented, the following rule should be followed.
hashCode will return the same value and compareTo will return 0 when equals returns true
If your objects will never participate in hash based collections or sorted collections, it's not necessary to follow that rule however, it will either limit what you can do or result in unexpected results.
I've seen this in one project. TreeSet is documented to contain one and one one of any object which equas is true. However, following the rule above, it actually uses compareTo returning 0 to do this. On this job someone wrote compareTo in a way inconsistant with the rule and as a result, doubles where going in and some objects where apparently randomly being excluded from the TreeSet.
Unless you have a large complelling reason to not follow the rules, I recommend you make it a habit. And any time you diviate prepare for some unexpected results.