根据 Java 文档, String
对象的 哈希码 计算如下:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using
int
arithmetic, wheres[i]
is the i th character of the string,n
is the length of the string, and^
indicates求幂。
为什么31用作乘数?
我理解乘数应该是一个比较大的素数。那么为什么不是 29 或 37,甚至 97?
原文由 jacobko 发布,翻译遵循 CC BY-SA 4.0 许可协议
根据 Joshua Bloch 的 Effective Java (一本推荐不够的书,由于在 stackoverflow 上不断提到,我买了这本书):
(来自第 3 章第 9 项:当您覆盖 equals 时始终覆盖 hashcode,第 48 页)