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?