在写hashcode时为什么要使用一个31这样的数
为什么在写hashcode时为什么要使用一个31这样的数,我用100,11,17是不是一样呢?有什么不一样的地方呢? --------------------编程问答-------------------- 31好像是什么东西的一个最小约数。有道理的(好像是hash表用来区分不同的空间的),忘记了,一般也没人去关注这个的。楼主愿意写几都行。 --------------------编程问答-------------------- 哪里看到的,贴来看下。 --------------------编程问答--------------------源代码里面有,好像是HashMap还是HashTable的,这个值应该是经验值,没有很明确的理论证明的 --------------------编程问答-------------------- 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.
31是素数
31*N
可以变成
N<<5-N
且5bit
补充:Java , Java SE