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?
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();
}
equals, it must override hashCodeequals and hashCode must use the same
set of fieldsequal, then their hashCode values must be equal as
wellimmutable, then hashCode is a candidate for caching
and lazy initializationYou 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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With