【问题标题】:Hash function returns same hash when keys have same length当键的长度相同时,哈希函数返回相同的哈希
【发布时间】:2019-10-30 01:28:08
【问题描述】:

我正在寻找 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_ahash_bcapacityp_prime 是什么?
  • 不能只取字符串的长度作为hash吗?

标签: java algorithm hash


【解决方案1】:

一个简单的解决方案只是将输入字符串的长度传递给任意散列函数。

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

// 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 ); 
}

【讨论】:

  • 但是如何使用容量以及我应该使用哪些参数来获取哈希?
猜你喜欢
  • 2018-03-23
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2015-09-08
  • 2012-06-09
相关资源
最近更新 更多