gpt4 book ai didi

java - 将字符串哈希值合并到主哈希值中

转载 作者:行者123 更新时间:2023-12-02 11:32:01 26 4
gpt4 key购买 nike

两个 String 对象的哈希合并是否应该与它们串联的哈希相同?我使用 XOR ^ 运算符(按照建议 here )并得到了不同的结果。

我做错了什么?

String a = "A";
String b = "B";
String ab = a+b;
int i = a.hashCode() ^ b.hashCode();

System.out.println(
a.hashCode()+"\n"+
b.hashCode()+"\n"+
ab.hashCode()+"\n"
i);

最佳答案

问题的前提是错误的。 hashCode() 的唯一硬性要求是两个相等的对象(即调用 a.equals(b) 返回 true)相等的哈希码(即 a.hashCode() == b.hashCode() 返回 true

事实上,通过阅读String#hashCode()'s javadoc ,它指出:

The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

很明显,连接两个字符串不会产生一个哈希码等于组成它的字符串的哈希码的异或的字符串。

关于java - 将字符串哈希值合并到主哈希值中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49223679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com