Tips and Pitfuls for overriding equals method in Java

If you’re a java developer, you already know Class java.lang.Object defines an equals method, which subclasses may override.
Here are some tips and pitfuls in implementing equals in this quick blog entry.  But before we diverge into some pointers, let’s review
the rules to override the equals method Java. As per following rule equals method in Java should be:
1) Reflexive : Object must be equal to itself.
2) Symmetric : if a.equals(b) is true then b.equals(a) must be true.
3) Transitive : if a.equals(b) is true and b.equals(c) is true then c.equals(a) must be true.
4) Consistent : multiple invocation of equals() method must result same value until any of properties are modified. So if two objects are equals in Java they will remain equals until any of there property is modified.
5) Null comparison : comparing any object to null must be false and should not result in NullPointerException. For example a.equals(null) must be false, passing unknown object, which could be null,  to equals in
Two Common Equals Pitfuls!
Mistake #1: Forgetting  hashCode()!.

RULE:  o1.equals(o2) implies o1.hashCode() == o2.hashCode()

This is very important. If you define a equals() method then you must define a hashCode() method as well. Also it means that if you have two objects that are equal then they must have the same hashCode, however the reverse is not true (i.e. if two objects have the same hashCode does not mean that they are equal). So, If a field is not used in equals(), then it must not be used in hashCode() method. (equals() and hashCode() relationship)

Mistake #2: Defining equals with the wrong signature.

This might be very obvious, but I have done this myself a few times!  Remember the equals method takes an Object in its method argument list.
// An wrong definition of equals
public boolean equals(Person other) {
  return (this.age() == other.getAge());
}
Mistake #3:  Not changing  hashcode when changing equals

Remember that If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Five Pointers
Tip #1: Use your IDE to automatically create the method.
The majority of  IDEs like NetBeans, Eclipse and IntelliJ IDEA provides support to generate equals() and hashcode() method.
In Eclipse do the right click-> source -> generate hashCode() and equals().
Tip #2: Do not over-complicate your comparisons.
If your domain class has any unique business key then just comparing that field in equals method would be enough instead of comparing all the fields e.g. in case of our example if “id” is unique for every Person and by just comparing id we can identify whether two Person are equal or not.
Tip #3: Remember hashCode!

While you override hashCode in Java,  make sure you use all fields which have been used in equals method in Java.

Tip #4: Be weary of StringBuffer
String and Wrapper classes like Integer, Float and Double override equals method, but StringBuffer doesn’t it.
Tip #5: General code practice

Whenever possible try to make your fields immutable by using final variables in Java, equals method based on immutable fields are more secure.

Published by anthonykuong

Anthony is a versatile Software professional with around 10 years of experience. He is a Full Stack developer experienced with clients in the Financial, Health and Supply Chain industries. He is experienced with MVC frameworks ( Spring Boot) , SPA frameworks ( Angular , VueJS), and also supports automated build deployments and packaging for development, qa, and production servers.. He has delivered rich user experience using Modern web technologies and techniques such are HTML5, CSS3, ECMAScript 6 (ES6)/ ECMAScript 2015, CSS pre-processors (SASS, Less), JavaScript build tools (Grunt, Gulp) , various UI Frameworks including AngularJS , Knockout JS , and CSS Frameworks including Bootstrap, and Foundation. He is adaptable to new technologies and frameworks. He is a rigorous, quality-conscious contributor with solid analytical skills. I can also be found on youtube - Youtube Channel: https://www.youtube.com/user/akuong/

Leave a comment