Best Practice To Implement Equals & HashCode Methods In Java
I came across this very interesting finding the other day and I asked myself why didn’t I already know this. Well, let me explain – I had this assignment where I had to implement Equals & HashCode methods in each Class. Why I was doing this – I got to compare objects of these classes to verify if they are “equal” or not. Double quotes around equal mean that the comparison was for the values and not just the object references.
Reminder #1: equals() method in java.util.Object is as good as “==” i.e. it only compares the object references and not the values.
Reminder #2: If a class has overridden equals method, it got to override hashcode method [Do you need me to tell why? If yes, let me know in the comments section below. I hope not to disappoint you
]