java学习----hashCode的计算

    xiaoxiao2022-07-06  215

    一、常见类型的几个案例

    class People{ } public class Test { public static void main(String[] args) { Integer a = 10; System.out.println(a.hashCode()); String str = "A"; System.out.println(str.hashCode()); Date date = new Date(); System.out.println(date.hashCode()); String ss = new String("123"); System.out.println(ss.hashCode()); People p = new People(); System.out.println(p); System.out.println(p.hashCode()); } }

    打印输出结果

    10 65 -553310500 48690 People@7852e922 2018699554

    二、分析

    1、integer类型的数据,返回的hash值为数据本身;

    2、对象类型的数据,返回的一串字符;

    3、String类型的数据,返回一串字符;

    三、源码的实现

    Object对hashCode()的方法实现

    public native int hashCode();

    String 对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; }

    Integer对hashCode()的实现

    @Override public int hashCode() { return Integer.hashCode(value); }

    四、了解下String对hashCode的计算

    1、在String对象的创建,都是将String数据拆分为char类型    private final char value[];

    2、对于计算hash值,为了区别"123"和"321"计算hash值一样的问题,对hash值计算时添加"权重"的思想;

    所以对于Stirng类型的hash值计算思路:

    public class Test { public static void main(String[] args) { String str = "ABC"; System.out.println(str.hashCode()); } }

    查询ascII码,我们知道A对应的十进制为65;B为66;C为67

    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; }

    他的计算过程为

    1、(31*0+'A')     65

    2、(31*0+'A')*31+'B'     65*31+66 = 2081

    3、((31*0+'A')*31+'B')*31+'C'   2081*31+67=64578

    最新回复(0)