重写hashCode中为什么基本都是乘以31

易德军 2011-06-17 04:31:23
看了许多源代码,看见在重写hashCode方法时,基本都是乘以31,不知道这到底是为什么?
...全文
379 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
降龙 2011-06-20
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ticmy 的回复:]

According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):

The value 31 was chosen because it is a……
[/Quote]
学习了。。。。
易德军 2011-06-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 ticmy 的回复:]
可能是数学家经过分析计算的,这个数可以让哈希更分散(个人想法)
[/Quote]


我确实也在《Effective Java 2》上看到,如此的说法

JavaMan_KA 2011-06-20
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ticmy 的回复:]
According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):

The value 31 was chosen because it is an o……
[/Quote]学习了。
eclipse_xu 2011-06-19
  • 打赏
  • 举报
回复
还有29
+1
dreamhunter_lan 2011-06-17
  • 打赏
  • 举报
回复
其实也可以是17这样的数~~~只要你喜欢
乀Lan 2011-06-17
  • 打赏
  • 举报
回复
应该是个人需要吧。。我在看老师写的代码的时候乘以1000
他说只要方便 怎么乘都行,
乘以31也是java的“潜规则”,就像创建类时候第一个字母要大写一样。
zqfddqr 2011-06-17
  • 打赏
  • 举报
回复
楼主是细心人啊哈哈哈
zqfddqr 2011-06-17
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ticmy 的回复:]
According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):

The value 31 was chosen because it is an……
[/Quote]还有这说学习了
龙四 2011-06-17
  • 打赏
  • 举报
回复
According to Joshua Bloch's Effective Java (a book that can't be recommended enough, and which I bought thanks to continual mentions on stackoverflow):

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.
龙四 2011-06-17
  • 打赏
  • 举报
回复
可能是数学家经过分析计算的,这个数可以让哈希更分散(个人想法)
chenchenyangll 2011-06-17
  • 打赏
  • 举报
回复
13 31 131 331 1313 这些数字都可以

个人认为,选这些数字仅仅是因为这样的hash算法更分散、效果更好

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧