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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM