Java - The equals and hashCode methods


How can we implement the equals method?

class Client {
  private int id;
  public Client(int id) { = id;

  public boolean equals(Object obj) {
    Client other = (Client) obj;
    if (id != {
      return false;
    return true;

  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + id;
    return result;

Why do we need to implement the hashCode method?

The implementation of hash code decides the effectiveness of Hashing. A good hashing function evenly distribute objects into different groups or buckets. A good hashCode method should have the following properties:

  1. if obj1.equals(obj2) is true, then obj1.hashCode() should be equals to obj2.hashCode()
  2. obj.hashCode() should return the same value when run multiple times if values of obj have not change.
  3. if obj1.equals(obj2) is false, it is not required that obj1.hashCode() is not equal to obj2.hashCode(). Two unequal objects MIGHT have the same hashCode.

The hashCode method is used when the object is put into a HashMap.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License