- public int hashCode() {
- int h = hash;
- if (h == 0) {
- int off = offset;
- char val[] = value;
- int len = count;
- for (int i = 0; i < len; i++) {
- h = 31*h + val[off++];
- }
- hash = h;
- }
- return h;
- }
实际上是使用霍纳法则计算
即
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 的值
选择31是因为他为素数,且他等于左移5位-1的值,vm会自动做这种优化
http://book.douban.com/subject/1610337/ lafore的这本书写的很人性化,没有太多公式,适合入门,第11章讲到了这部分
http://en.wikipedia.org/wiki/Java_hashCode()
http://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier
http://www.ibm.com/developerworks/java/library/j-jtp05273/index.html