c# - string.GetHashCode() 唯一性和冲突

标签 c# .net

给定两个不同的字符串,s.GetHashCode() != s1.GetHashCode() 是否总是这样?

是否是不同整数的个数小于不同字符串的个数?

最佳答案

没有。就像一个简单的思想实验:有多少个字符串(提示:比 232 多得多,因此可以有多少个唯一的哈希码(提示:232. See the problem? )

每当 Equals 返回两个对象相等时,哈希码只需要相等。此外,只要两个散列码相等,那么对象本身就不可能相等。没有进一步的要求,但它们应该分布良好,以便哈希表可以良好地执行。所以基本上是:

enter image description here

请注意省略了相应的 ⇐ 变体。这不是等价,只是两个含义。

引用documentation :

A hash function must have the following properties:

  1. 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.

  2. 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.

  3. 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/

相关文章:

c# - 从另一个类继承的类的构造函数是否效率较低?

c# - 如何知道谁在处置我的 Bitmap 对象或处置了它?

c# - 如何使用 Entity Framework 构建具有 "Core"数据库和各个派生数据库的 ASP.NET MVC 应用程序?

c# - 将带有换行符的文本转换为列表<String>

c# - 移动远程程序

c# - 图像回调 c++ 到 c#

.net - 是否有用于组织/按字母顺序排列 CSS、JSON 对象等的工具或库?

.net - 确定 TTF 字体文件名

c# - 如何将 IEumerable 集合添加到队列并在 .NET 中异步处理每个项目?

c# - C# 中的枚举类型