当键具有相同的长度时,哈希函数返回相同的哈希



我正在寻找java中的哈希函数,对于具有相同长度的键返回相同的哈希。

            int index1 = hashmap.hash("xxx");
            int index2 = hashmap.hash("yyy");
            assertEquals(index1, index2);

我正在使用这个函数:

public int hash(String x) {
    int hashCode = x.hashCode();
    return (int) ( ( Math.abs( hash_a * hashCode + hash_b) % p_prime ) % capacity ); 
}
一个简单的

解决方案是将输入字符串的长度传递给任意哈希函数。

由于您将传递字符串的长度,因此可以通过对函数进行一些更改来完成,如下所示:

// hash_a, hash_b, p_prime, and capacity variables are defined in a class.
public int hash(String x) {
    int hashCode = x.length(); // this line is updated
    return (int) ( ( Math.abs( hash_a * hashCode + hash_b) % p_prime ) % capacity ); 
}

最新更新