Best implementation for hashCode method for a collection

后端 未结 20 2915
难免孤独
难免孤独 2020-11-22 01:39

How do we decide on the best implementation of hashCode() method for a collection (assuming that equals method has been overridden correctly) ?

相关标签:
20条回答
  • 2020-11-22 02:18

    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.

    0 讨论(0)
  • 2020-11-22 02:20

    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.

    0 讨论(0)
  • 2020-11-22 02:20

    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.

    0 讨论(0)
  • 2020-11-22 02:21

    Use the reflection methods on Apache Commons EqualsBuilder and HashCodeBuilder.

    0 讨论(0)
  • 2020-11-22 02:22

    There's a good implementation of the Effective Java's hashcode() and equals() logic in Apache Commons Lang. Checkout HashCodeBuilder and EqualsBuilder.

    0 讨论(0)
  • 2020-11-22 02:23

    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

    0 讨论(0)
提交回复
热议问题