Contents    Page-10    Prev    Next    Page+10    Index   

Hash Function

We want a hash function to be easy to compute and to avoid clustering , the hashing of many keys to the same value.

One hash function that is usually good is to treat the key (e.g., a string of characters) as an integer and find the remainder modulo a prime p:


int hash = key % p;
Since this produces an integer from 0 to p - 1, we make the array size p.

The Java .hashCode() for String is roughly: [from Wikipedia.]


public static int hashCode(String input) {
    int h = 0;
    int len = input.length();
    for (int i = 0; i < len; i++) {
        h = 31 * h + input.charAt(i);
    }
    return h; }