If you are preparing for java certification exam, then while studying hashcodes and collections, you must have encountered one statement. Here we are going to learn about equals and hashcode methods in java.
If you are overriding equals() method then also override hashcode() method because all the data structures that use hashing, use hashcodes for considering object equality. If the hashcode of two objects are not equal, then objects cannot be equal.
What exactly this statement mean? We will directly try to implement by a program. We have a Bike class which of course can create Bike objects.
We will create bikes in a different class and try to add them into HashSet. The criteria for our bikes to be equal is that their engine capacity and color should be same. If they are same, they are equal bikes. Thats why we have overridden equals method accordingly in the Bike class.
Now, HashSet is a data structure that stores unique elements,duplicates not allowed. Let us test this by adding equal strings in a HashSet and bikes in a different HashSet.
For strings, HashSet behaved correctly, two strings are equal, so only one was added in it and size is 1. But what happened in case of bikes? Two bikes are meaningfully equal, as we have overridden the equals method for it. but why does HashSet is allowing duplicate elements? That means according to HashSet, they are not equal. This fails the condition of equals elements in hashset. What is wrong?
The only thing wrong about this is we are not overriding hashcode method for Bike class. As HashSet uses hashing, and objects must be equal if and only if their hashcodes are equal, we must override hashcode() for Bike class.
So let us do it now. Bike class is updated as follows.