最近被提及Java中HashMap的一些实现及哈希冲突等,不知不觉就想到哈希值到底是怎么计算出来的,正文如下。
结论:
对于String、Integer等类复写了Object中的hashCode方法的类来说,有各自的实现方法
Object类中的hashCode()该方法是一个本地方法,Java将调用本地方法库对此方法的实现
代码,
public class Test {
public static void main(String[] args) {
String str = "hello";
String str2 = "world";
String str3 = "a";
String str4 = "1";
Integer i = 1;
System.out.println("hello的 hashcode = "+str.hashCode());
System.out.println("world的 hashcode = "+str2.hashCode());
System.out.println("a的 hashcode = "+str3.hashCode());
System.out.println("字符串1的 hashcode = "+str4.hashCode());
System.out.println("整数对象1的 hashcode = "+i.hashCode());
String str5 = "abc";
System.out.println("abc的 hashcode = "+str5.hashCode());
String str6 = "abc ";
System.out.println("abc 的 hashcode = "+str6.hashCode());
}
}
代码的输出结果如下:
hello的 hashcode = 99162322
world的 hashcode = 113318802
a的 hashcode = 97
字符串1的 hashcode = 49
整数对象1的 hashcode = 1
abc的 hashcode = 96354
abc 的 hashcode = 2987006
可以直观的看到,a字符的哈希值是97,是它的ASCII码值。然后整数对象的哈希值是它本身。经过查看源码,发现,hash值的计算,不同类型计算方式不同。具体实现如下:
Integer类的 hashcode() 方法在Integer类中被复写了,源码如下:
@Override
public int hashCode() {
return Integer.hashCode(value);
}
public static int hashCode(int value) {
return value;
}
Integer类的hashcode返回的就是Integer本身的值。
对于String来说,具体的源码如下:
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
String对象会对对象的内容进行计算,得出hash值。
对于字符来说,像字符a会被转换为对应的ACII码值,也就是97,由于char的位数少于int型的位数,所以31*h+val[i] 计算时会被强制转换为int值。
验证计算,
abc的hashcode值为96354,那么即为 31*(31*(31*0+97)+98)+99=96354
空格的ASCII码值为32,所以 "abc " hashcode 为 96354*31+32 = 2987006
对于上文举例的String和Integer来说是复写了hashCode方法,以上述方式计算了hash值。
————————————————
原文链接:https://blog.csdn.net/i_am_tomato/article/details/106130258