I have a task to implement a hash code of a string in java using the definition. I wrote this code.
public int hash(String str) {
int hashValue = 0;
int power;
for (int i = 0; i < str.length(); i++) {
power = (str.length() -1 - i);
hashValue = hashValue + str.charAt(i) * (int) Math.pow(31, power);
}
return hashValue;
}
I found out that the result in my method is the same as hashcode() only for strings with a length lower than 8. Is this supposed to be that way or my method isn't accurate? I've seen that maybe the hash code has changed for the string over 8 chars.
Look at hashCode implementation in jdk:
public static int hashCode(byte[] value) {
int h = 0;
int length = value.length >> 1;
for (int i = 0; i < length; i++) {
h = 31 * h + getChar(value, i);
}
return h;
}
It might happen, that your method produces the same result as this one. It does not matter, actually. It is just a hashing method.
Note, that hashing method does not need to be "accurate". It is a way of reducing an arbitrary object (string) to an int. You can use any method you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With