Java Hashcode and equals – Most Important Things to Consider

291 Flares Twitter 0 Facebook 4 Google+ 287 LinkedIn 0 291 Flares ×

What is a HashCode

Hashcode is a method defined in the java.lang.Object class that returns a hash value. A hash is nothing but  a 32 bit signed integer. In Java, all class should provide a hashCode() method. The value of the hash is required to store the object effectively in data structures like hash tables. The hash value is used to group objects into buckets for the efficient storage and retrieval. By default every class inherits the default implementation provided by the java.lang.Object but this may not be efficient or accurate for specific user defined classes and hence many override this to provide the hash computed based on the class specific attributes.

The Contract

Java expects the hashCode and the equals method to behave in a related manner. If  two objects are found to be equal then the hashCode method should return the same value. But the specification is not that strict if the two objects are unequal. If two objects are unequal then it is very desirable for them to return different hash values but this is not mandatory. But keep in mind that if they are equal they should return the same hash. Make it a practice to override hashCode when you override equals.

What to look for while overriding hashCode

Providing a good hash function is important if you want to maximize the performance and storage efficiency of the collections storing your objects. The simple goal is to implement a  hash function that provides uniform distribution (discrete) of  hash values. A uniform distribution means there is a equal probability of  returning a value out of the N possible outcomes. For example if you throw a dice there is an equal probability of getting a 1, 2, 3, 4,5 or 6 . The probability getting a value is 1/6. It is very difficult practically to provide a perfect hash function.

Best way to implement a hash function for your object

Apache Commons Language library has a HashCodeBuilder that can be used to provide hash implementation. For example consider a class  Employee.

Or you can use the typical implementation provided by many IDE’s like Eclipse.

In the above code, we assign a prime number as hash and them multiply it with another prime number ( any prime number) and adding the hashcode of the fields to it. This way we will ensure maximum uniform distribution of the hash value.

To implement the equals you can use the EqualsBuilder from Apache Commons.

Remember always override hashCode and equals together