If you do not override hashCode() , then each of your instances will have hashcode computed from some predefined Hashing algorithm in the Object class. Thus, all your instances will probably have different hash values (this is not the case yet). So, each instance will go into its bucket.
Now, even if you override the equals() method to make two instances equal based on some attribute, their hash codes are still different.
So, two instances with different hash codes can never be equal. Thus, the size of the set is 3. Since it has no duplicates.
But when you override hashCode() with the following implementation: -
public int hashCode() {return size/5};
It will return the same value for the same size . This way, instances with the same size value will have the same hash codes, and also, since you compared them in the equals method based on size , therefore they will be equal and therefore they will be considered duplicate in your Set and therefore will be deleted . So Set.size() is 2.
Moral : - You should always override hashCode() whenever you override the equals() method in order to maintain a common contract between the two methods.
General contract between hashcode and equals method : -
- When two objects are equal, their hash code must be equal
- If two objects are not equal, their hash code may be equal
- The hashCode algorithm should always generate the same value for the same object.
- If hashCode for two objects is different, they will not be equal
- Always use the
same attributes to calculate the hashcode that you used to compare two instances
It is strongly recommended to read at least once : -
source share