Suppose that m distinct keys are presented to a hash table of size m using hash function h.

Then the mean length of a chain is 1.0.

Suppose that P(k) is the probability that key k is presented to the hash table.

Ideally, for each of the slots j = 0, 1, ..., m-1, we want the sum of the probabilities of the keys hashing to j to be 1/m.

But it is rare that we can know the probability distribution P.

Most of the time, hashing methods must be heuristic — good, but not guaranteed to be perfect.

Recall that for integers i and k, i mod k is the integer remainder when dividing i by k.

That remainder must be in the set {0, 1, ..., k-1}.

When hash table keys are integers, it is straightforward to transform them to indexes in the set {0, 1, ..., m-1}, where m is the size of the hash table:

h(k) = k mod m

If a hash table key is not an integer, it can be converted to one, and then hashed using mod.

For example, for keys that are strings, the integer values of the characters can be combined into one integer by summing them. If sum is initialized to zero, then for each character ch in the string do:

sum = sum + ch;

However, different strings with the same characters, for example "eat" and "tea", should hash to different values.

This can be accomplished by incorporating a prime multiplicative factor in the computation:

sum = 31 * sum + ch;

Now a different power of 31 is involved in the summing of the characters.

It is possible that this method will overflow an integer's capacity and become negative. In that case use the static Math.abs method to keep it positive.