Combining Java hashcodes into a “master” hashcode

后端 未结 2 1821
被撕碎了的回忆
被撕碎了的回忆 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).

提交回复
热议问题