两个字符串的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;
    }

可知

str.charAt(0) * 31^(n-1) + str.charAt(1) * 31^(n-2) + ... + str.charAt(n-1)

那我们最简单的操作就是当n=2的时候

x1*31 + x2 = y1*31 + y2

可得(x1-y1) * 31 = y2 - x2;

大家可以去查查Ascii表中的Ascii码 找出x1,x2与y1,y2满足上面式子的情况

我这边找到的是"3C"与"2B"

发布了16 篇原创文章 · 获赞 3 · 访问量 2030

猜你喜欢

转载自blog.csdn.net/Cia_zibo/article/details/104870197