Java 当键具有相同的长度时,哈希函数返回相同的哈希值
我在java中寻找一个哈希函数,对于相同长度的键,它返回相同的哈希值Java 当键具有相同的长度时,哈希函数返回相同的哈希值,java,algorithm,hash,Java,Algorithm,Hash,我在java中寻找一个哈希函数,对于相同长度的键,它返回相同的哈希值 int index1 = hashmap.hash("xxx"); int index2 = hashmap.hash("yyy"); assertEquals(index1, index2); 我正在使用此功能: public int hash(String x) { int hashCode = x.hashCode(); retur
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 );
}
什么是
hash_a
,hash_b
,容量
,和p_prime
?你不能把字符串的长度作为hash吗?但是容量是如何工作的?我应该使用哪些参数来获取hash?