Why GetHashCode() matters?

前端 未结 2 1005
深忆病人
深忆病人 2020-12-10 17:16

I am trying to understand what the object.GetHashCode() is used for. I read that it is used by collections to uniquely identify keys. But I wanted to test this

相关标签:
2条回答
  • 2020-12-10 18:03

    GetHashCode is only the first check, used to determine non-equality and possible equality. After that, Equals is checked. Which for objects defaults to reference-equality, and for structs is a memberwise compare. Override Equals to give an appropriate implementation (paired with the hash-code), and it should give the results you expect (duplicate key).

    btw, the IDE is probably already giving you a warning that GetHashCode and Equals should always be treated together...

    0 讨论(0)
  • 2020-12-10 18:14

    Hash codes are used as a first check to divide objects into groups. If a collection holds the hash code of each item therein, it can search for an item by first searching for items whose hash code matches that of the item sought. Once it finds one or more such items, it can examine them in more detail. Ideally, objects which are not equal would always return different hash codes, but that's not practical. If objects which are not equal return identical hash codes, it may be necessary to examine all of them in detail any time one of them is sought.

    0 讨论(0)
提交回复
热议问题