SE450: Java classes: Hash Code [17/22] Previous pageContentsNext page

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:

  1. Compute a hash code for each significant field. A field is considered significant if it is part of the equals implementation. For primitive types, the hashcode is the type as an integer. For a reference type, it is the hashCode (if it is not null)
  2. Combine the fields into the hash code.

The combination can be done as follows:

  1. Bitwise-or hash = hash << n | c where n is an arbitrary integer, say 8.
  2. Addition hash = hash * p + c where p is a prime number, say 37

The 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

Previous pageContentsNext page