Sobes.tech
Middle

How does object comparison work in HashSet?

sobes.tech AI

Answer from AI

In HashSet, object comparison occurs in two stages:

  1. 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.
  2. Equality comparison: If the hash codes are equal, the equals(Object o) method is called for a detailed comparison. If equals() returns true, 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 calling hashCode() on each of them must return the same integer value.
  • If two objects are not equal according to the equals(Object o) method, then calling hashCode() 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 in equals comparisons 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.

How does object comparison work in HashSet? — Java - sobes.tech