String 的hashcode方法:
String str = "abcdef";
h = 31 * (31* (31 * (31 * (31 * (31 * (0) + 'a') + 'b') + 'c') + 'd') + 'e')+'f';
自己写了一个测试程序验证改hash算法对不对:
package Example_4_3;
public class Example4_3_1 {
public static void main(String[] args) {
System.out.println("abcdef.hashcode = " + "abcdef".hashCode());
System.out
.println("abcdef.owner = "+ (31 * (31 * (31 * (31 * (31 * (31 * (0) + 'a') + 'b') + 'c') + 'd') + 'e') + 'f'));
}
}
最后运行一下之后结果如下:
abcdef.hashcode = -1424385949
abcdef.owner = -1424385949
由此可以看出String类的hashcode算法就是以31为基数,
基数的选择规律:必须是质数,因为质数只能被1和本身整除,这样任何数乘以一个整数更容易产生唯一性,不会被重复,减少散列(hashcode值)的冲突。
至于为什么选择31,而不是其他数字,是观测结果后的一个选择,原因不明,也有人反对使用31,认为数字太小,这样更容易产生冲突,需要选择更大的质数。