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

后端 未结 6 1431
囚心锁ツ
囚心锁ツ 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:45

    Java 8 adds Long.hashCode(long) to the JDK.

    The following code could yield higher performance. This code reduces the calculation to 32-bit int instead of computing with 64-bit long. This can make a difference on 32-bit and smaller architectures. 32-bit processes on x86 machines could optimize this into a single instruction which simply XORs 2 registers.

    return (int)(value ^ (value >>> 32));

    As noted in other answers, this does not have a good avalanche effect and hence could lead to collisions. One could go with cryptographic hash functions to ensure high avalanche effect. However, there are other algorithms such as Murmur Hash (more information) which have very good avalanche effect but don't consume as much CPU time.

提交回复
热议问题