简体   繁体   English

Object.GetHashCode

[英]Object.GetHashCode

My question may duplicate Default implementation for Object.GetHashCode() but I'm asking again because I didn't understand the accepted answer to that one. 我的问题可能会重复Object.GetHashCode()的默认实现,但我再问一次,因为我不理解那个问题的接受答案。

To begin with I have three questions about the accepted answer to the previous question , which quotes some documentation as follows: 首先,我对上一个问题的接受答案有三个问题,引用了一些文档如下:

"However, because this index can be reused after the object is reclaimed during garbage collection, it is possible to obtain the same hash code for two different objects." “但是,因为在垃圾回收期间回收对象后可以重用此索引,所以可以为两个不同的对象获取相同的哈希码。”

Is this true? 这是真的? It seems to me that two objects won't have the same hash code, because an object's code isn't reused until the object is garbage collected (ie no longer exists). 在我看来,两个对象将不具有相同的哈希码,因为在对象被垃圾收集(即不再存在)之前不会重用对象的代码。

"Also, two objects that represent the same value have the same hash code only if they are the exact same object." “另外,表示相同值的两个对象只有在完全相同的对象时才具有相同的哈希码。”

Is this a problem? 这是一个问题吗? For example, I want to associate some data with each of the node instances in a DOM tree. 例如,我想将一些数据与DOM树中的每个节点实例相关联。 To do this, the 'nodes' must have an identity or hash code, so that I can use them as keys in a dictionary of the data. 为此,“节点”必须具有标识或哈希码,以便我可以将它们用作数据字典中的键。 Isn't a hash code which identities whether it's "the exact same object", ie "reference equality rather than "value equality", what I want? 是不是一个哈希码来识别它是否是“完全相同的对象”,即“引用相等而不是”值相等“,我想要什么?

"This implementation is not particularly useful for hashing; therefore, derived classes should override GetHashCode" “这个实现对于散列并不是特别有用;因此,派生类应该覆盖GetHashCode”

Is this true? 这是真的? If it's not good for hashing, then what if anything is it good for, and why is it even defined as a method of Object? 如果它对散列不好,那么如果它有什么好处,为什么它甚至被定义为Object的方法呢?


My final (and perhaps most important to me) question is, if I must invent/override a GetHashCode() implementation for an arbitrary type which has "reference equality" semantics, is the following a reasonable and good implementation: 我的最终(也许对我来说最重要的)问题是,如果我必须发明/覆盖具有“引用相等”语义的任意类型的GetHashCode()实现,则以下是一个合理且良好的实现:

class SomeType
{
  //create a new value for each instance
  static int s_allocated = 0;
  //value associated with this instance
  int m_allocated;
  //more instance data
  ... plus other data members ...
  //constructor
  SomeType()
  {
    allocated = ++s_allocated;
  }
  //override GetHashCode
  public override int GetHashCode()
  {
    return m_allocated;
  }
}

Edit 编辑

FYI I tested it, using the following code: 仅供参考我使用以下代码测试它:

    class TestGetHash
    {
        //default implementation
        class First
        {
            int m_x;
        }
        //my implementation
        class Second
        {
            static int s_allocated = 0;
            int m_allocated;
            int m_x;
            public Second()
            {
                m_allocated = ++s_allocated;
            }
            public override int GetHashCode()
            {
                return m_allocated;
            }
        }
        //stupid worst-case implementation
        class Third
        {
            int m_x;
            public override int GetHashCode()
            {
                return 0;
            }
        }

        internal static void test()
        {
            testT<First>(100, 1000);
            testT<First>(1000, 100);
            testT<Second>(100, 1000);
            testT<Second>(1000, 100);
            testT<Third>(100, 100);
            testT<Third>(1000, 10);
        }

        static void testT<T>(int objects, int iterations)
            where T : new()
        {
            System.Diagnostics.Stopwatch stopWatch =
                System.Diagnostics.Stopwatch.StartNew();
            for (int i = 0; i < iterations; ++i)
            {
                Dictionary<T, object> dictionary = new Dictionary<T, object>();
                for (int j = 0; j < objects; ++j)
                {
                    T t = new T();
                    dictionary.Add(t, null);
                }
                for (int k = 0; k < 100; ++k)
                {
                    foreach (T t in dictionary.Keys)
                    {
                        object o = dictionary[t];
                    }
                }
            }
            stopWatch.Stop();
            string stopwatchMessage = string.Format(
                "Stopwatch: {0} type, {1} objects, {2} iterations, {3} msec",
                typeof(T).Name, objects, iterations,
                stopWatch.ElapsedMilliseconds);
            System.Console.WriteLine(stopwatchMessage);
        }
    }

On my machine the results/output are as follows: 在我的机器上,结果/输出如下:

First type, 100 objects, 1000 iterations, 2072 msec
First type, 1000 objects, 100 iterations, 2098 msec
Second type, 100 objects, 1000 iterations, 1300 msec
Second type, 1000 objects, 100 iterations, 1319 msec
Third type, 100 objects, 100 iterations, 1487 msec
Third type, 1000 objects, 10 iterations, 13754 msec

My implementation takes half the time of the default implementation (but my type is bigger by the size of my m_allocated data member). 我的实现占用了默认实现的一半时间(但是我的类型因我的m_allocated数据成员的大小而变大)。

My implementation and the default implementation both scale linearly. 我的实现和默认实现都是线性扩展的。

In comparison and as a sanity check, the stupid implementation starts bad and scales worse. 相比之下,作为一个健全性检查,愚蠢的实施开始变坏并且变得更糟。

The most important property a hash code implementation must have is this: 哈希代码实现必须具有的最重要的属性是:

If two objects compare as equal then they must have identical hash codes. 如果两个对象相等,那么它们必须具有相同的哈希码。

If you have a class where instances of the class compare by reference equality, then you do not need to override GetHashCode; 如果你有一个类,通过引用相等比较类的实例,那么你不需要重写GetHashCode; the default implementation guarantees that two objects that are the same reference have the same hash code. 默认实现保证两个具有相同引用的对象具有相同的哈希代码。 (You're calling the same method twice on the same object, so of course the result is the same.) (你在同一个对象上调用两次相同的方法,所以当然结果是一样的。)

If you have written a class which implements its own equality that is different from reference equality then you are REQUIRED to override GetHashCode such that two objects that compare as equal have equal hash codes. 如果您编写了一个实现与引用相等不同的自身相等的类,那么您需要重写GetHashCode,这样两个比较相等的对象具有相同的哈希码。

Now, you could do so by simply returning zero every time. 现在,您可以通过每次返回零来实现。 That would be a lousy hash function, but it would be legal. 这将是一个糟糕的哈希函数,但它是合法的。

Other properties of good hash functions are: 良好散列函数的其他属性是:

  • GetHashCode should never throw an exception GetHashCode永远不应该抛出异常

  • Mutable objects which compare for equality on their mutable state, and therefore hash on their mutable state, are dangerously bug-prone. 可变对象比较其可变状态的相等性,因此在其可变状态上进行哈希处理,这些对象很容易出错。 You can put an object into a hash table, mutate it, and be unable to get it out again. 您可以将对象放入哈希表中,对其进行修改,并且无法再将其删除。 Try to never hash or compare for equality on mutable state. 尝试永远不要散列或比较可变状态的相等性。

  • GetHashCode should be extremely fast -- remember, the purpose of a good hash algorithm is to improve the performance of lookups. GetHashCode应该非常快 - 请记住,良好的哈希算法的目的是提高查找的性能。 If the hash is slow then the lookups can't be made fast. 如果哈希很慢,则无法快速查找。

  • Objects which do not compare as equal should have dissimilar hash codes, well distributed over the whole range of a 32 bit integer 不相等的对象应具有不同的哈希码,在32位整数的整个范围内均匀分布

Question: 题:

Is this true? 这是真的? It seems to me that two objects won't have the same hash code, because an object's code isn't reused until the object is garbage collected (ie no longer exists). 在我看来,两个对象将不具有相同的哈希码,因为在对象被垃圾收集(即不再存在)之前不会重用对象的代码。

Two objects may share the same hash code, if it is generated by default GetHashCode implementation, because: 如果默认的GetHashCode实现生成,则两个对象可以共享相同的哈希代码,因为:

  1. Default GetHashCode result shouldn't be changed during object's lifetime , and default implementation ensures this. 在对象的生命周期内不应更改默认的GetHashCode结果 ,默认实现可确保这一点。 If it could change, such types as Hashtable couldn't deal with this implementation. 如果它可以改变,像Hashtable这样的类型无法处理这种实现。 That's because it's expected that default hash code is a hash code of unique instance identifier (even although there is no such identifier :) ). 那是因为预期默认哈希码是唯一实例标识符的哈希码(即使没有这样的标识符:))。
  2. Range of GetHashCode values is range of integer (2^32). GetHashCode值的范围是整数范围(2 ^ 32)。

Conclusion: It's enough to allocate 2^32 strongly-referenced objects to (must be easy on Win64) to reach the limit. 结论: 足够分配2 ^ 32个强引用对象(必须在Win64上很容易)才能达到极限。

Finally, there is an explicit statement in object.GetHashCode reference in MSDN : The default implementation of the GetHashCode method does not guarantee unique return values for different objects. 最后, MSDN中的object.GetHashCode引用中有一个显式语句:GetHashCode方法的默认实现不保证不同对象的唯一返回值。 Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. 此外,.NET Framework不保证GetHashCode方法的默认实现,并且它返回的值在不同版本的.NET Framework之间是相同的。 Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes. 因此,此方法的默认实现不得用作散列目的的唯一对象标识符。

You do not actually need to modify anything on a class which requires only reference equality. 实际上,您不需要修改只需要引用相等的类的任何内容。

Also, formally, that is not a good implementation since it has poor distribution. 而且,正式地说,这不是一个好的实施,因为它的分配很差。 A hash function should have a reasonable distribution since it improves hash bucket distribution, and indirectly, performance in collections which use hash tables. 散列函数应该具有合理的分布,因为它改进了散列桶分布,并且间接地改善了使用散列表的集合中的性能。 As I said, that is a formal answer, one of the guidelines when designing a hash function. 正如我所说,这是一个正式的答案,是设计哈希函数时的指导原则之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Object.GetHashCode()的实现 - Implementation of Object.GetHashCode() 将Object.GetHashCode()转换为Guid - Converting Object.GetHashCode() to Guid Object.GetHashCode()对引用或值是唯一的吗? - Is Object.GetHashCode() unique to a reference or a value? 如何在重写GetHashCode()的类型上使用Object.GetHashCode() - How to use Object.GetHashCode() on a type that overrides GetHashCode() 关于如何正确覆盖object.GetHashCode()的一般建议和指南 - General advice and guidelines on how to properly override object.GetHashCode() 在没有不可变字段的类中重写Object.GetHashCode()时要返回什么? - What to return when overriding Object.GetHashCode() in classes with no immutable fields? 我的IEquatable仍在使用Object.GetHashcode for Dictionary <T> [] - My IEquatable is still using Object.GetHashcode for Dictionary<T>[] .NET SHA256与Object.GetHashCode() - .NET SHA256 Vs Object.GetHashCode() C#运算符重载:Object.Equals(object o)和Object.GetHashCode() - C# operator overloading: Object.Equals(object o) & Object.GetHashCode() 警告:“...覆盖Object.Equals(对象o)但不覆盖Object.GetHashCode()” - Warning: “… overrides Object.Equals(object o) but does not override Object.GetHashCode()”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM