首页 > 其他 > 详细

hashCode值的生成规则

时间:2019-10-12 19:33:09      阅读:98      评论:0      收藏:0      [点我收藏+]

转载于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)); }

hashCode值的生成规则

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!