Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java objects are equal though hashcode is different

While reading about equals() and hashcode(), I came to know that if two objects are equal, then their hashcodes must be equal, though not vice-versa.

But below example doesn't reflect this.

class Employee{

  private String name;

  Employee(String name){
    this.name = name;
  }

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

}

Now if I create two Employee objects as

Employee e1 = new Employee("hi");
Employee e2 = new Employee("hi");

If i do, e1.equals(e2), it returns true even though their hashcodes are different which is evident from printing, e1.hashcode() and e2.hashcode().

Can someone explain me?

like image 434
Anand Avatar asked Jan 20 '26 07:01

Anand


1 Answers

You need to override hashcode method and provide implementation which is in contract with equals.

   @Override
    public int hashCode() {
        return name == null ? 0 : name.hashCode();
    }
  • if a class overrides equals, it must override hashCode
  • when they are both overridden, equals and hashCode must use the same set of fields
  • if two objects are equal, then their hashCode values must be equal as well
  • if the object is immutable, then hashCode is a candidate for caching and lazy initialization

You can read about implementing hashcode here

If you don't override the method default behavior will be used from Object class.

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

Hash based [HashMap,HashSet,Hashtable,LinkedHashSet,WeakHashMap] collections will use hashCode() to find/store objects in buckets and then they will call equals().

like image 137
Amit Deshpande Avatar answered Jan 23 '26 17:01

Amit Deshpande