Implement hashCode() method

We have to be more careful while implementing the hashCode in any model classes. Otherwise you will see an erroneous behavior while using that model object in any collection classes.

Apache Commons lang contains a utility class HashCodeBuilder. We can leverage this class in our model classes.

Please refer the below code. Here the HashCodeBuilder constructor takes two parameters. The first one is initialOddNumber and next one is multiplierOddNumber. It would be if you give it as prime Numbers.

You can also append the super class fields with appendSuper(int) method

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

public class User {

    private String name;
    private int age;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public boolean equals(Object o) {
        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        User user = (User) o;

        return new EqualsBuilder()
                .append(age, user.age)

    public int hashCode() {
        HashCodeBuilder hashCodeBuilder = new HashCodeBuilder(1, 3);//initialNonOddNumber, multiplyOddNumber
        hashCodeBuilder.append(age); //Once you append the age, then hashCode is computed as 1*3+12 = 15.
        hashCodeBuilder.append(name);//After that the 15 is considered as the initial number. then 15*3+3556498 = 3556543
        return hashCodeBuilder.toHashCode();

    public static void main(String[] args) {
        User user = new User();
        user.setAge(12); //hashCode is 12
        user.setName("test"); //hashCode is 3556498. You can verify this by printing "test".hashCode()
        System.out.println(user.hashCode());//Hashcode is 3556543

You could also use reflection, but make sure that you should change the AccessibleObject.setAccessible as true for accessing private fields. but basically using reflection will slow down the application

 public int hashCode() {
   return HashCodeBuilder(1,3).reflectionHashCode(this);


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s