Good Hash Function for Strings

A good hash function for strings should have the following properties:

  1. Uniformity: The function should distribute the strings uniformly across the hash table.
  2. Efficiency: The function should be efficient to compute.
  3. Non-sensitivity to small changes: The function should not produce drastically different hash values for small changes in the input string.
  4. Low collision rate: The function should produce a low collision rate, meaning that different input strings should not produce the same hash value.

One widely used hash function for strings is the DJB2 hash function. It has good performance and a low collision rate. Here is the Java implementation of the DJB2 hash function:

public static int djb2(String str) {
    int hash = 5381;
    for (int i = 0; i < str.length(); i++) {
        hash = ((hash << 5) + hash) + str.charAt(i);
    }
    return hash;
}

You can use the DJB2 hash function as follows:

int hash = djb2("hello");
System.out.println(hash); // prints "99162322"

I hope this helps. Let me know if you have any questions.