SE450: Java classes: Hash Code [17/22] ![]() ![]() ![]() |
The Hashcode is used in collections classes such as HashSet
and HashMap
. If the equals method is overridden, it is
necessary to override the hashCode method.
In general, it can be done as follows:
The combination can be done as follows:
hash = hash << n | c
where n is an arbitrary integer, say 8.hash = hash * p + c
where p is
a prime number, say 37The key is to make sure that the hashcode is always the same for equal values. If it isn't, a value can be put in a hashtable, and then never be able to be retrieved