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

Java 为什么我的哈希函数会收到负值?,java,arrays,function,hash,overflow,Java,Arrays,Function,Hash,Overflow,我有一个散列函数,它根据单词ASCII值的乘积计算一个键。当我用小词测试它时,它工作得很好,但后来我尝试了整个文本文件中的词,其中一些得到负值,而另一些是正值。我知道这是溢出,但我如何修复它 编辑: 好的,人们说负散列值是有效的。我的问题是,我使用数组实现了哈希表,由于负数,我得到了一个索引越界错误。解决这个问题的最佳方法是什么 public int asciiProduct(String word) { // sets the calculated value of the word to

我有一个散列函数,它根据单词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;
}
public int-asciiProduct(字符串字){
//将单词的计算值设置为0
int-wordProductValue=1;
//对于单词中的每个字母,它都会得到它的ascii值
//并将其乘以单词ProductValue
for(int i=0;i
负散列码是完全有效的。这没什么问题。不需要“修复”。
但我可以问你为什么要这样做吗


word.hashCode()
应该会给你一个比这个更好的哈希值

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

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

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

if(hash<0)return-hash不适用于-2^31(一个int可以拥有的最小值)。@markspace-没想到abs(-2^31)也会产生一个否定的结果,我直到现在才知道。我被要求实现各种散列函数作为赋值。是的,负散列码是有效的。我更新了我的问题-我的问题是,我正在使用数组实现哈希表,负值给我一个索引越界异常。请使用
&
而不是模:
index=hash&(length-1)