previous | start | next

A Sample hash function for Java Strings

Recall the general principle about the Java hashCode() method inherited from Object:

        If x.equals(y) returns true, then x.hashCode() should equal y.hashCode()
     

The Java String class overrides both the equals and the hashCode methods. The first method returns true if two Strings represent the same sequence of characters, not just if they are identical as objects. So hashCode was rewritten so that two equal strings return equal hash values.

But to be a "good" hash function, we also would like to have two different String values return different hash values.

So a "good" hash function for String should involve all the characters in the string and it should not give the same value for permutations of the same string.

E.g, "bat" and "tab" should return different hash values.



previous | start | next