执⾏代码
public class Demo06 {
public static void main(String[] args) { String s=\"hello\";
System.out.println(s.hashCode()); }}
以下是hashCode()源码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; }
分析:以对象直接调⽤hashCode()⽅法为例 hashCode()⽅法在java.lang.String类下 功能是返回此字符串的哈希码
先判断传⼊的值长度⼤于o,再分拆成并保存⾄char[]数组,通过for()遍历, 调⽤hashCode公式h = 31 * h + val[i];
以传⼊hello为例,通过ASCII码表 h 104,e 101, l 108,o 111 h=31*0+104 h=104 h=31*104+101 h=3325 h=31*3325+108 h=103183 h=31*103183+108 h=3198781 h=31*3198781+111 h=99162322 最后return h的数值,返回给调⽤者
如有错误还请⼤佬多多指点,⼩弟在此多谢。
因篇幅问题不能全部显示,请点此查看更多更全内容