Why GetHashCode is in Object class?

前端 未结 7 1587
故里飘歌
故里飘歌 2021-01-04 20:57

Why GetHashCode is part of the Object class? Only small part of the objects of the classes are used as keys in hash tables. Wouldn\'t it be better to have a separate interfa

7条回答
  •  迷失自我
    2021-01-04 21:20

    GetHashCode is in object so that you can use anything as a key into a Hashtable, a basic container class. It provides symmetry. I can put anything into an ArrayList, why not a Hashtable?

    If you require classes to implement IHashable, then for every sealed class that doesn't implement IHashable, you will writing adapters when you want to use it as key that include the hashing capability. Instead, you get it by default.

    Also Hashcodes are a good second line for object equality comparison (first line is pointer equality).

提交回复
热议问题