JDK中String的hashCode方法的实现

JDK中String的hashCode方法的实现方法如下:
1 public int hashCode() {
2 int h = hash;
3 int len = count;
4 if (h == 0 && len > 0) {
5 int off = offset;
6 char val[] = value;
7
8 for (int i = 0; i < len; i++) {
9 h = 31*h + val[off++];
10 }
11 hash = h;
12 }
13 return h;
14 }
对于为什么选取31而不是32作为基数,下面两个链接中的讨论解释了这个问题,概括起来就是使用31可以有效的减少冲突,32会使不同字符串取得相同hashCode的概率大幅增加。
http://www.coderanch.com/t/329128/java/java/Java-String-hashcode-base-computation
http://www.javamex.com/tutorials/collections/hash_function_technical_2.shtml
posted on 2011-04-06 16:28  Kadin Zhu  阅读(1286)  评论(0)    收藏  举报