将字符串散列合并到主散列中

Merge of String hashes into master hash

两个 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) returns true)具有相等的哈希码(即 a.hashCode() == b.hashCode() returns 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.)

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