为什么我的哈希函数接收到负值?

时间:2014-12-09 02:13:24

标签: java arrays function hash overflow

我有这个哈希函数,它根据单词ASCII值的乘积计算一个键。当我用小词测试它时工作正常,但后来我尝试了整个文本文件中的单词,其中一些得到负值而其他人都是正面的。我知道这是溢出的,但我该如何解决呢?

编辑: 好的,所以人们都说负哈希值是有效的。我的问题是我使用数组实现了哈希表,并且由于负数而得到索引超出范围的错误。解决这个问题的最佳方法是什么?

public int asciiProduct(String word) {
  // sets the calculated value of the word to 0
  int wordProductValue = 1;

  // for every letter in the word, it gets the ascii value of it
  // and multiplies it to the wordProductValue
  for (int i = 0; i < word.length(); i++) {
    wordProductValue = wordProductValue * (int) word.charAt(i);
  }

  // the key of the word calculated by this function will be set 
  // to the modulus of the wordProductValue with the size of the array
  int arrayIndex = wordProductValue % (hashArraySize-1);
  return arrayIndex;
}

2 个答案:

答案 0 :(得分:1)

你可以取整数乘法结果的绝对值 - 当整数值太大时,它将溢出为负数。

wordProductValue = Math.abs(wordProductValue * (int) word.charAt(i));

但是,通过%运算符使用模数的哈希函数即使使用负数也应该仍然有效。

答案 1 :(得分:0)

负哈希码完全有效。没有什么问题。无需“修复”。 但我可以问你为什么要这样做?

word.hashCode()应该给你一个更好的哈希值,而不是......