Best implementation for hashCode method for a collection

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

提交回复
热议问题