给定两个不同的字符串,s.GetHashCode() != s1.GetHashCode()
是否总是这样?
是否是不同整数的个数小于不同字符串的个数?
最佳答案
没有。就像一个简单的思想实验:有多少个字符串(提示:比 232 多得多,因此可以有多少个唯一的哈希码(提示:232. See the problem? )
每当 Equals
返回两个对象相等时,哈希码只需要相等。此外,只要两个散列码不相等,那么对象本身就不可能相等。没有进一步的要求,但它们应该分布良好,以便哈希表可以良好地执行。所以基本上是:
请注意省略了相应的 ⇐ 变体。这不是等价,只是两个含义。
引用documentation :
A hash function must have the following properties:
If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.
The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
For the best performance, a hash function must generate a random distribution for all input.
关于c# - string.GetHashCode() 唯一性和冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11607206/