Probability of getting a duplicate value when calling GetHashCode() on strings

前端 未结 6 1549
遥遥无期
遥遥无期 2020-11-30 10:49

I want to know the probability of getting duplicate values when calling the GetHashCode() method on string instances. For instance, according to th

6条回答
  •  一个人的身影
    2020-11-30 11:38

    I think all that's possible to say is "small, but finite and definitely not zero" -- in other words you must not rely on GetHashCode() ever returning unique values for two different instances.

    To my mind, hashcodes are best used when you want to tell quickly if two instances are different -- not if they're the same.

    In other words, if two objects have different hash codes, you know they are different and need not do a (possibly expensive) deeper comparison.

    However, if the hash codes for two objects are the same, you must go on to compare the objects themselves to see if they're actually the same.

提交回复
热议问题