Skip to content

Instantly share code, notes, and snippets.

@bfchengnuo
Last active April 29, 2019 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bfchengnuo/4a34307675abddbb113343c50eccd563 to your computer and use it in GitHub Desktop.
Save bfchengnuo/4a34307675abddbb113343c50eccd563 to your computer and use it in GitHub Desktop.
Java重写hashCode用31?

在OSChina 中看到了一篇文章《Java 中正确使用 hashCode 和 equals 方法》,看到 hashCode 的方法体内的 31 比较有意思。

在Stackoverflow上找到了解释,但没完全看明白,大概意思是说31这个值是一个奇素数,只是一个默认的传统

并不一定要用 31。

但是这个数可以通过位移的方式来处理乘法,获得一些性能上的优化,虚拟机会自动做这些优化。

http://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier


总结来说,一般有如下两个原因:

第一,31 是一个不大不小的质数,是作为 hashCode 乘子的优选质数之一。另外一些相近的质数,比如 37、41、43 等等,也都是不错的选择。那么为啥偏偏选中了 31 呢?请看第二个原因。

第二、31 可以被 JVM 优化,31 * i = (i << 5) - i

当然,选择尽可能小的数乘法运算后也容易避免溢出。

https://segmentfault.com/a/1190000010799123

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment