hashCode

xxx

其实一直觉得31这个挺碍眼的,不知道是处于什么考虑

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

//而小黑哥的通用工具类里面,定义的ApiResult也使用了这样的hashCode方式
public int hashCode() {
        int result = status;
        result = 31 * result + (message != null ? message.hashCode() : 0);
        result = 31 * result + (data != null ? data.hashCode() : 0);
        return result;
    }


//"s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]"

yyy

其实都是在使用31作为基数,把值转换为31进制,来获得更大的唯一性

1、 31 * N 会被编译器优化为=> 左移5位 - N
2、 质数能更好地保证与其他数相乘之后的唯一性
3、 研究人员发现,31能更好的分配key,减少碰撞,但是不知道为什么

zzz

参考文章=> 这个人废话了一大堆,然后说他也不知道为什么使用31。。。

“Researchers found that using a prime of 31 gives a better distribution to the keys, and lesser no of collisions.
No one knows why, the last i know and i had this question answered by Chris Torek himself, who is generally credited with coming up with 31 hash, on the C++ or C mailing list a while back.”

不知道是不是我翻译有问题。。反正这句话我没找到答案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值