Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't Hashtables and dictionaries use Equals() method instead of GetHashCode for keys comparision in .NET?

In .NET, Whenever we override Equals() method for a class, it is a normal practice to override the GetHashCode() method as well. Doing so will ensure better performance when the object is used in Hashtables and Dictionaries. Two keys are considered to be equal in Hashtable only if their GetHashCode() values are same. My question is why can't the Hashtables use Equals() method to compare the keys?, that would have removed the burden of overriding GetHashCode() method.

like image 321
DivideByzero Avatar asked Oct 21 '25 04:10

DivideByzero


1 Answers

HastTable/Dictionaries use Equals in case of collision (when two hash codes are same).

Why don't they use only Equals ?

Because that would require a lot more processing than accessing/(comparing) integer value value (hash code). (Since hash codes are used as index so they have the complexity of O(1))

like image 156
Habib Avatar answered Oct 23 '25 19:10

Habib