高效的 hashCode() 实现 [英] Efficient hashCode() implementation

查看:37
本文介绍了高效的 hashCode() 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用 IntelliJ IDEA 自动生成一个类的 hashCode() 方法,通常该方法采用以下形式:

I often auto-generate an class's hashCode() method using IntelliJ IDEA and typically the method takes the form:

result = 31 * result + ...

我的问题是乘以 31 的目的是什么?我知道这是一个质数,但为什么要特别选择 31?此外,如果为一个特别小的/大的数据集实现一个 hashCode(),人们会以不同的方式处理这个问题吗?

My question is what is the purpose of multiplying by 31? I know this is a prime number but why pick 31 specifically? Also, if implementing a hashCode() for a particularly small / large dataset would people approach this problem differently?

推荐答案

乘以 31 很快,因为 JIT 可以将其转换为左移 5 位和减法:

Multiplying by 31 is fast because the JIT can convert it to a shift left by 5 bits and a subtract:

x * 31 == (x << 5) - x

没有任何特别的额外信息,我会坚持这种方法.它相当快,并且可能最终得到合理分布的哈希码,而且也很容易正确:)

Without any particular extra information, I'd stick to this approach. It's reasonably fast and likely to end up with reasonably well-distributed hash codes, and it's also easy to get right :)

数据集的大小并不重要,但如果您有关于将要使用的值的特定额外信息(例如它总是偶数"),那么您可能设计更好的哈希函数.不过,我会等到它是一个实际问题的时候:)

The size of the dataset doesn't really matter, but if you have particular extra information about the values you'll be work with (e.g. "it's always even") then you may be able to design a better hash function. I'd wait until it's an actual problem first though :)

这篇关于高效的 hashCode() 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆