How does the Set collection determine whether the object is duplicate

In the Set collection, judging whether an object is repeated depends on the implementation of the object's hashCode() and equals() methods. When an element is added to the Set collection, the hashCode() method of the element will be called first to get its hash value, and then compared with the hash value of the existing elements in the set, if the hash value is the same, then call the element's equals() method to compare, if the equals() method also returns true, the element is considered to be a duplicate and will not be added to the collection.

Therefore, if you want to add an object to the Set collection and want to be able to correctly determine whether the object is a duplicate, you need to ensure that the implementation of the hashCode() and equals() methods of the object meet the requirements, namely:

  1. The hash value returned by the hashCode() method should be stable, that is, if the equals() method of two objects returns true, their hashCode() method return values ​​should be equal.
  2. The equals() method should be able to correctly compare two objects for equality, that is, the equals() method should return true if every property value of the two objects is equal.

It should be noted that if a class does not override the hashCode() and equals() methods, the implementation in the Object class will be used by default, which is usually not required. Therefore, when implementing a custom class, be sure to override the hashCode() and equals() methods correctly.

Guess you like

Origin blog.csdn.net/qq_42133976/article/details/130417277