且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么要向hashCode()添加一个常量?

更新时间:2023-11-12 14:33:34

以非零值开头在哈希码溢出或%非2的幂的情况下在概念上有帮助,这导致更多的位是不同的比较值,与之相比,溢出那些没有.

Starting with non zero value helps notionally when the hashCode overflows or is % by a non power of two which results in more bits being different comparing values which overflow compared to those which don't.

小常量不如大常量有效,但可以使用更少的字节并更快.例如.* 31更快,但可能不如* 109.

Small constants are not as effective as larger ones but can use less bytes and be faster. E.g. * 31 is faster but might not be as effective as * 109.

其区别取决于您的用例.

The difference it make depends on your use case.

注意:使用数字选择存储区后,即使确保您具有唯一的hashCode也不能确保没有冲突.

Note: even ensuring you have unique hashCodes doesn't ensure you have no collisions after the number has been used to select a bucket.