I have this hash function that calculates a key based on the product of a words ASCII values. It was working fine when I tested it with small words, but then I tried words from a whole text file and some of them get negative values while others are positive. I understand that this is overflow, but how would I fix it?
EDIT: Ok, so people are saying that negative hash values are valid. My problem is that I implemented the hash table using an array and I am getting an index out of bounds error due to the negative numbers. What would be the best way to fix this?
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;
}
You can just take the absolute value of the result of your integer multiplication - which will overflow to a negative number when the integer value gets too big.
wordProductValue = Math.abs(wordProductValue * (int) word.charAt(i));
However, your hash function using modulo via the %
operator should still work even with a negative number.
A negative hash code is perfectly valid. There is nothing wrong with it. No need to "fix". But may I ask why are you doing this?
word.hashCode()
should give you a much better hash value, than this ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.