Home » Core Java » hashCode() method and its contract

hashCode() method and its contract

What is hashCode() method and explain its contract ?

hashCode() method is defined in the top level class of Java i.e. Object class .

Syntax :

The hashCode() method defined by Object class returns distinct integers for distinct objects.This is typically implemented by converting the internal address of the object into an integer.

Contract of hashCode() method :
1. Whenever hashCode() method is invoked on the same object more than once during an execution of a Java application, the hashCode() method must consistently return the same integer, provided no information
used in equals(Object) comparisons on the object is modified.This integer need not remain consistent from one execution of an application to another execution of the same application.
2. If two objects are equal according to the equals(Object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.
3. It is not equired that if two objects are unequal according to the equals() method, then calling the hashCode() method on each of the two objects must produce distinct integer results.However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
4. if a class overrides equals(Object) method, it must override hashCode().

How to override hashCode() method ?
In the below program I have shown how to override hashCode() method.

Steps to override hashCode() method:
1. Take two variables prime and result.The initial value of result is 1 and intitial value of prime can be 5,7,17 or 31 etc.Use of prime number, results in distinct hashcode() for distinct object.
2. If the any of the memebr is null ,then add 0 to the result otherwise add hashCode() value of the member variable to result.

3. Repeat step2 for all member variable.
4. Return result.

To generate equals() and hashCode(),right click on the class,then on source and then click on Generate hashCode() and equals()


Leave a comment

Your email address will not be published. Required fields are marked *

1 × 5 =