Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best implementation for hashCode method for a collection

How do we decide on the best implementation of hashCode() method for a collection (assuming that equals method has been overridden correctly) ?

like image 959
Omnipotent Avatar asked Sep 22 '08 06:09

Omnipotent


People also ask

Where hashCode method is implemented?

“As much as is reasonably practical, the hashCode() method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)”

What makes a good hashCode function?

equals , must have the same hashCode. hashCode values should be spread as evenly as possible over all ints. hashCode should be relatively quick to compute. hashCode must be deterministic (not random).

Which method is used to get the hashCode of the given object?

To get this hashcode value for an object, we can use the hashcode() method in Java. It is the means hashcode() method that returns the integer hashcode value of the given object. Since this method is defined in the Object class, hence it is inherited by user-defined classes also.


1 Answers

The best implementation? That is a hard question because it depends on the usage pattern.

A for nearly all cases reasonable good implementation was proposed in Josh Bloch's Effective Java in Item 8 (second edition). The best thing is to look it up there because the author explains there why the approach is good.

A short version

  1. Create a int result and assign a non-zero value.

  2. For every field f tested in the equals() method, calculate a hash code c by:

    • If the field f is a boolean: calculate (f ? 0 : 1);
    • If the field f is a byte, char, short or int: calculate (int)f;
    • If the field f is a long: calculate (int)(f ^ (f >>> 32));
    • If the field f is a float: calculate Float.floatToIntBits(f);
    • If the field f is a double: calculate Double.doubleToLongBits(f) and handle the return value like every long value;
    • If the field f is an object: Use the result of the hashCode() method or 0 if f == null;
    • If the field f is an array: see every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next.
  3. Combine the hash value c with result:

    result = 37 * result + c 
  4. Return result

This should result in a proper distribution of hash values for most use situations.

like image 157
dmeister Avatar answered Sep 21 '22 07:09

dmeister