Search code examples
javahashcode

How can we write a polynomial hash function with given prime


So for a given prime number 31, how can I write a hash function for a string parameter?

Here is my attempt.

    private int hash(String key){
        int c = 31;
        int hash = 0;
    
        for (int i = 0; i < key.length(); i++ ) {
            int ascii = key.charAt(i);
            hash += c * hash + ascii; 
    }
        return (hash % sizetable);} // sizetable is an integer which is declared outside. You can see it as a table.length().

So, since I can not run any other function in my work and I need to be sure about the process here, I need your answers and help! Thank you so much.


Solution

  • Your implementation looks quite similar to what is documented as standard String.hashCode() implementation, this even uses also 31 as prime factor, so it should be good enough.

    I just would not assign 31 to a variable, but declare a private static final field or use it directly as magic number - not OK in general, but might be OK in this case.

    Additionally you should add some tests - if you already know about the concept of unit tests - to prove that your method gives different hashes for different strings. And pick the samples clever, so they are different (for the case of the homework ;)