Best implementation for hashCode method for a collection

后端 未结 20 3062
难免孤独
难免孤独 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: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.

提交回复
热议问题