equals() method is used to determine the equality of two objects.
When we say equality, it should adhere by the following properties,
Reflexive: Always, a = a. In Java, a.equals(a) should always be true.
Symmetric: If a = b, then b = a. In Java, if a.equals(b) is true, then b.equals(a) should be true.
Transitive: If a = b and b = c, then a = c. In Java, if a.equals(b) and b.equals(c) is true, then a.equals(c) should be true.
Your equals() doesnot confront to this rules.
Moreover according to javadoc - It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. So we may face some problem using this implementation of equals() while natural sorting
Good approach for overriding equals method in Java
- Do this check -- if yes then return true.
- Do null check -- if yes then return false.
- Do the instanceof check
- Type cast the object
- Compare individual attribute starting with numeric attribute because comparing numeric attribute is fast and use short circuit operator for combining checks. If first field does not match, don't try to match rest of attribute and return false.