Overriding equals and hashCode in Java


equals() (javadoc) must define an equality relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore

The equals method implements an equivalence relation. It is:

  •  Reflexive: For any non-null reference value x, x.equals(x) must return true.
  •  Symmetric: For any non-null reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true.
  •  Transitive: For any non-null reference values x, y, z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.
  •  Consistent: For any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  •  For any non-null reference value x, x.equals(null) must return false.


hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).
The relation between the two methods is:
Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute equals() to compute hashCode().
an example:
  
public class Employee {

 public String empName;
 public int empId;
 
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + empId;
  result = prime * result + ((empName == null) ? 0 : empName.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;
  Employee other = (Employee) obj;
  if (empId != other.empId)
   return false;
  if (empName == null) {
   if (other.empName != null)
    return false;
  } else if (!empName.equals(other.empName))
   return false;
  return true;
 }
}

You can get Eclipse to generate the two methods for you: Source > Generate hashCode() and equals()

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...