Middle
How does object comparison work in HashSet?
sobes.tech AI
Answer from AI
In HashSet, object comparison occurs in two stages:
- Hash code comparison: First, the
hashCode()method is called on the objects being compared. If the hash codes are not equal, the objects are considered different, and no further comparison is needed. - Equality comparison: If the hash codes are equal, the
equals(Object o)method is called for a detailed comparison. Ifequals()returnstrue, the objects are considered the same.
For HashSet (and other hash-based collections) to work correctly, the hashCode() and equals() methods must be properly overridden and follow the contract:
- If two objects are equal according to the
equals(Object o)method, then callinghashCode()on each of them must return the same integer value. - If two objects are not equal according to the
equals(Object o)method, then callinghashCode()on each of them does not necessarily have to return different integer values. However, returning different hash codes for unequal objects can improve hash table performance. - When calling
hashCode()on the same object within a single Java application execution, it should return the same integer value, provided that the information used inequalscomparisons does not change.
When adding an element to a HashSet, it first computes the object's hash code to determine the bucket where the element will be placed. Then, within this bucket (which can be a list or a tree depending on the implementation), it compares the added object with existing elements in the bucket using a combination of hash code and equals(). If an object with the same hash code and equal according to equals() is found, the new element will not be added, as HashSet does not allow duplicates.