Combining Java hashcodes into a “master” hashcode

后端 未结 2 1819
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 09:19

I have a vector class with hashCode() implemented. It wasn\'t written by me, but uses 2 prime numbers by which to multiply the 2 vector components before XORing them. Here i

相关标签:
2条回答
  • 2020-12-17 10:11

    The reason for using prime numbers (they don't necessarily have to be "large" prime numbers) is indeed to avoid common factors.

    Hash codes are used by hash-based collection classes such as HashSet and HashMap. They work best if the hash codes of objects in the map are as dissimilar as possible (they have to do more work to distinguish objects if the hash code of those objects is the same).

    Multiplying the hash codes of the parts that you use to make a combined hash code with primes ensures that the parts will not have common factors, so there's less chance of collisions (with regard to the hash codes of different parts overlapping each other).

    0 讨论(0)
  • 2020-12-17 10:22

    That's the normal practice. It looks pretty reasonable to me. If you're using Eclipse, you should find that it can generate equals and hashCode for you—just check the Source menu. It will do the same thing—enumerate your fields and create an equals method that checks all of them, then choose n prime numbers and do what you've done to create a hashCode method.

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