Best implementation for hashCode method for a collection

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

    If you use eclipse, you can generate equals() and hashCode() using:

    Source -> Generate hashCode() and equals().

    Using this function you can decide which fields you want to use for equality and hash code calculation, and Eclipse generates the corresponding methods.

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

    When combining hash values, I usually use the combining method that's used in the boost c++ library, namely:

    seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2);
    

    This does a fairly good job of ensuring an even distribution. For some discussion of how this formula works, see the StackOverflow post: Magic number in boost::hash_combine

    There's a good discussion of different hash functions at: http://burtleburtle.net/bob/hash/doobs.html

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