When to Override equals and hashCode in Java Class


While doing programming in java we are writing many class for many different purpose and in general we are writing class members and using them. But as every class is derived from Object class in java and object class has some methods with very special purpose. Most of the time we do not need to override them but many time we should think about whether we should override them or not.

If you are going to use your object in code where comparison is required then you must override equals and hashCode methods and you should use .equals method to do comparison as == check only reference mean it will return true only when both variables are referencing to same object.

While overriding equals and hashCode you can use all attributes of your class or some key attributes. See below product class and that is perfect for it’s purpose

public class Product implements Serializable {

  private static final long serialVersionUID = -7492639752670189553L;
  private String productId;
  private String categoryId;
  private String name;
  private String description;

  public String getProductId() {
    return productId;
  }

  public void setProductId(String productId) {
    this.productId = productId.trim();
  }
  //..........

}

But when we want to check equality of two product object paged on some key(categoryId) then you must have to override equals method and hashCode as given below

@Override
public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                        + ((categoryId == null) ? 0 : categoryId.hashCode());
        return result;
}

@Override
public boolean equals(Object obj) {
        if (this == obj)
                return true;
        if (obj == null)
                return false;
        if (getClass() != obj.getClass())
                return false;
        Product other = (Product) obj;
        if (categoryId == null) {
                if (other.categoryId != null)
                        return false;
        } else if (!categoryId.equals(other.categoryId))
                return false;
        return true;
}

Now you can compare two object of Person using .equals method.

You can also add more field in equals and hashCode method as per your need.