What are the rules I should follow to ensure GetHashCode() method returns unique value for an object?

时光总嘲笑我的痴心妄想 提交于 2019-12-13 22:19:46

问题


What are the rules I should follow to ensure GetHashCode() method returns unique value for an object?

For example:

  • Should I include some prive members for the calculation?
  • Should I multiply instead of sum?
  • Can I be sure that I am generating a uniqe hash code for a particular object graph? etc.

回答1:


You shouldn't even aim for GetHashCode() returning a unique value for each object. That's not the point of GetHashCode().

Eric Lippert has a great post about hash codes which you should read thoroughly. Basically you want to end up with something which will always return the same value for two equal objects (and you need to work out what you mean by equal) and is likely to return different values for two non-equal objects.

Personally I tend to use an implementation like this:

public override int GetHashCode()
{
    int hash = 17;
    hash = hash * 31 + field1.GetHashCode();
    hash = hash * 31 + field2.GetHashCode();
    hash = hash * 31 + field3.GetHashCode();
    ...
    return hash;
}

Things to watch out for:

  • If you have mutable objects, be careful! You shouldn't mutate an object after using it as the key in a hash map.
  • If your fields can be null, you need to check for that while calculating your hash. For example:

    hash = hash * 31 + (field2 == null ? 0 : field2.GetHashCode());
    



回答2:


You don't necessarily need a fool proof hashcode because you also need to override Equals for comparison. Usually what I do is take the values I know are different across objects, concatenate them into a string and return the hash for that.




回答3:


I think your answer is here: See Jon Skeet answer, generally pretty reliable way to calculate it. Proved by time :)

What is the best algorithm for an overridden System.Object.GetHashCode?



来源:https://stackoverflow.com/questions/7312336/what-are-the-rules-i-should-follow-to-ensure-gethashcode-method-returns-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!