Wednesday, 8 October 2014

How to override hashCode method

Java collections like HashTable and HashMap works on hashing principle while storing and retrieving the data. Under ideal conditions, these hash based collections offer constant time retrieval and insert operations. A properly written hash function distributes the objects uniformly in buckets. There are situations like, you need to override the hashCode method of Object class. This post explains you how to override the hashCode method.

There is a contract between hashCode and equals method, If you override one of these methods, you must override both. Check the link for the relation between hashCode and equals method.

How to override hashCode method
1.   Define a variable ‘hash’, value of hash should be any prime number like 5, 7, 13, 97 etc.,
        Example: int hash = 7;

2.   Take another prime number as multiplier, It is always good to use other prime than the variable ‘hash’. Lets say the multiplier is 47.
        Example: int multiplier = 47;

3.   Use the below formula to compute the hash code.
        hash = multiplier * hash + (variable hash code)
       
Here variable represents all the variables that you want to use to compute hash code for this object.
import java.util.Date;

public class Employee {
    private int id;
    private Date joiningDay;
    private int noticePeriod;
    String firstName, lastName;

    Employee(int id, Date joiningDay, int noticePeriod){
        this.id = id;
        this.joiningDay = joiningDay;
        this.noticePeriod = noticePeriod;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Employee other = (Employee) obj;
        if (this.id != other.id) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 47 * hash + this.id;
        hash = 47 * hash + (this.joiningDay != null ? this.joiningDay.hashCode() : 0);
        hash = 47 * hash + this.noticePeriod;
        return hash;
    }
}

As you observe the hashCode snippet, while calculating the hash code for reference types (joiningDay), we checked whether it is null or not.

hash = 47 * hash + (this.joiningDay != null ? this.joiningDay.hashCode() : 0);
 
You may like


                                                 Home

No comments:

Post a Comment