Re: Comment on how to uniquely track your objects in C# / hash table / get hash code

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



raylopez99 <raylopez99@xxxxxxxxx> wrote:
But, here is a philosophical problem to consider: how often does the
IL engine (sorry in advance for any wrong terminology) assign the same
hash code id to two different objects? Very, very rare, but it
happens. Then, when this happens, you'll get an error when you use
GetHashCode or Object.ReferenceEquals(), no? Has anybody thought
about this problem?

Yes, they certainly have. When you look something up in a hashtable,
first you need to find all the items that have the same hashcode as the
key that you're trying to look up. Then you need to call Equals to find
out whether each candidate entry is *actually* a match for the key
you're using.

Hash collisions slow things down (because you need to call Equals on
more candidate entries) but they don't stop a hashtable from actually
working correctly. Just don't try to treat a hashcode as a unique
identifier - it isn't.

--
Jon Skeet - <skeet@xxxxxxxxx>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
.



Relevant Pages

  • Re: Comment on how to uniquely track your objects in C# / hash table / get hash code
    ... hash code id to two different objects? ... first you need to find all the items that have the same hashcode as the ... Second question: with Equals, and I've seen examples of customized ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: how to prevent duplicate objects in HashMap???
    ... > class has a hashCode method which simply returns the id of the object. ... The purpose of the hash code is as a *hint* to let the ... but just looped through the collection trying equals() on everything. ... That would make hashed collections very inefficient, ...
    (comp.lang.java.programmer)
  • Re: hashCode() for Custom classes
    ... I am currently faced with the task of providing a logical equals() ... have to override the hashCode() so that when an object of this class ... String name; ... The hash code of Agent is the combined hash code of ...
    (comp.lang.java.programmer)
  • Re: equals and hashCode
    ... >> I understand the purpose of overriding equals() in comparing the data of ... >> hashCode() is a little less clear. ... >> "Equal objects must produce the same hash code as long as they are equal, ...
    (comp.lang.java.programmer)
  • hashCode() for Custom classes
    ... I am currently faced with the task of providing a logical equals() ... have to override the hashCode() so that when an object of this class ... String name; ... The hash code of Agent is the combined hash code of ...
    (comp.lang.java.programmer)