Set and Uniqueness in Set
In this topic, we are going to learn the logic behind a set that finds the uniqueness of an object being added and understand the importance of two object-level methods.
The magic lies in two methods of the Object class
hashCode()
equals()
Basic Rules for the equals() and hashCode() Methods
Two objects can be identical only when the value returned using the hashcode() method is identical and the equal() method returns true.
If the two objects return the same hashCode() value, it doesn't necessarily mean both objects are the same (as hash values may collide with other objects as well). In that case, it's necessary to find the equality by calling equals() and verifying the identity.
We can't use hashCode() alone to find out the equality; we need to use equals() as well to do this. However, hashCode() alone is enough to find the inequality. If the hashCode() returns different values, it's safe to consider the objects different.
Adding an Object to a Set
Though many things...