How should I map long to int in hashCode()?

后端 未结 6 1432
囚心锁ツ
囚心锁ツ 2020-12-25 11:10

I have a range of objects that have a long field whose value uniquely identifies a particular object across my entire system, much like a GUID. I have overriden

6条回答
  •  时光取名叫无心
    2020-12-25 11:21

    You have understood the purpose of hashCode correctly. Yes, an uniform distribution is desirable (although not an actual requirement).

    I would suggest ((id >> 32) ^ id).

    The above expression:

    • Uses all bits of the original value, does not discard any information upfront. For example, depending on how you are generating the IDs, the upper bits could change more frequently (or the opposite).
    • Does not introduce any bias towards values with more ones (zeros), as it would be the case if the two halves were combined with an OR (AND) operation.

提交回复
热议问题