How do we decide on the best implementation of hashCode()
method for a collection (assuming that equals method has been overridden correctly) ?
If you're happy with the Effective Java implementation recommended by dmeister, you can use a library call instead of rolling your own:
@Override
public int hashCode() {
return Objects.hashCode(this.firstName, this.lastName);
}
This requires either Guava (com.google.common.base.Objects.hashCode
) or the standard library in Java 7 (java.util.Objects.hash
) but works the same way.
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.
I prefer using utility methods fromm Google Collections lib from class Objects that helps me to keep my code clean. Very often equals
and hashcode
methods are made from IDE's template, so their are not clean to read.
Use the reflection methods on Apache Commons EqualsBuilder and HashCodeBuilder.
There's a good implementation of the Effective Java's hashcode()
and equals()
logic in Apache Commons Lang. Checkout HashCodeBuilder and EqualsBuilder.
about8.blogspot.com, you said
if equals() returns true for two objects, then hashCode() should return the same value. If equals() returns false, then hashCode() should return different values
I cannot agree with you. If two objects have the same hashcode it doesn't have to mean that they are equal.
If A equals B then A.hashcode must be equal to B.hascode
but
if A.hashcode equals B.hascode it does not mean that A must equals B