Contents    Page-10    Prev    Next    Page+10    Index   

Hash Function for Strings

It isn't always easy to find a good hash function; statistical tests are needed to ensure that the distribution of values is good. Java provides the function hashCode() that can be used for strings.


public static int jenkinshash(String key) {
    int hash = 0;
    for (int i = 0; i < key.length(); i++) {
        hash += key.charAt(i);
        hash += (hash << 10);
        hash ^= (hash >> 6); }
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    return hash; }
public static int hashfix(int hashcode, int size) {
    hashcode %= size;
    if ( hashcode < 0 ) hashcode += size;
    return hashcode; }

The function jenkinshash is by Bob Jenkins, Dr. Dobbs Journal, 1997; this returns a 32-bit integer that could be negative. The function hashfix makes a hash code positive and returns the hash code modulo the table size, which should be prime.