Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare hashCode implement

Tags:

java

hash

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.

like image 224
Amit Nachimovitz Avatar asked Apr 08 '26 11:04

Amit Nachimovitz


1 Answers

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.

like image 71
Viacheslav Shalamov Avatar answered Apr 11 '26 01:04

Viacheslav Shalamov