hashCode值的生成规则

转载于https://blog.csdn.net/zjq_1314520/article/details/78955104

1、对于integer源码如下:

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

  

public static int hashCode(int value) {
        return value;
    }

  可以看出value就是对应的hashcode值

2、对于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;
    }

  可以看出其value为依次遍历其每个字符成员,递归的将当前的hashcode* 31 +下一个成员对应的ascII值

eg:  String s = "10";

"1"   ----> 49

"0" ------->48

h = 31 * 0 + 49       h = 49

h = 31 * 49 + 48     h = 1567

  Long类型源码如下:     

可以看出其值为当前值与当前逻辑右移32位之后异或得出的值
 public static int hashCode(long value) {
        return (int)(value ^ (value >>> 32));
    }

public static int hashCode(long value) { return (int)(value ^ (value >>> 32)); }

原文地址:https://www.cnblogs.com/otways/p/11663388.html