How do we decide on the best implementation of hashCode()
method for a collection (assuming that equals method has been overridden correctly) ?
First make sure that equals is implemented correctly. From an IBM DeveloperWorks article:
- Symmetry: For two references, a and b, a.equals(b) if and only if b.equals(a)
- Reflexivity: For all non-null references, a.equals(a)
- Transitivity: If a.equals(b) and b.equals(c), then a.equals(c)
Then make sure that their relation with hashCode respects the contact (from the same article):
- Consistency with hashCode(): Two equal objects must have the same hashCode() value
Finally a good hash function should strive to approach the ideal hash function.