Re: about Equals and GetHashCode
- From: Marc Gravell <marc.gravell@xxxxxxxxx>
- Date: Thu, 12 Jun 2008 07:39:52 -0700 (PDT)
No; GetHashCode() does not guarantee uniqueness - for starters, it is
an Int32 - it would take a trivial example involving Int64 and i++ to
show that they aren't unique.
The point is that if a.GetHashCode() and b.GetHashCode() are
*different* then a nd b definitely aren't the same. If the hashcodes
are the same, then you need to check a and b. This provides an
efficient way of narrowing down the amount of things we actually need
to check, by first excluding everything that doesn't have the same
hashcode,
leaving a much smaller set.
Further, advanced structures such as hash-tables can use the hash-code
to create "buckets" - so, for example, based on the number of items,
it might decide to split it into 20 "buckets" by taking the modulo of
the hashcode - i.e. each item goes into the bucket with index
GetHashCode() % bucketCount.
Then, to find a given item, it can do:
* get the haschode of the search key
* calculate the modulo of that hashcode - we now know which bucket to
look in [down to 1/20th of the data already]
* look in that bucket for everything with the correct hashcode
[probably down to 1 or 2 items now]
* perform the actual Equals between the search key and the stored
items, to find the one we want
So: GetHashCode() is very rarely used without Equals() [although
Equals() can be used without GetHashCode()]; it is definitely very
important, and underpins all the fast lookups from Dictionary<,>, etc.
Linear search (testing each item) would be very, very slow on a long
list.
Marc
.
- Follow-Ups:
- Re: about Equals and GetHashCode
- From: Marc Gravell
- Re: about Equals and GetHashCode
- References:
- about Equals and GetHashCode
- From: Tony Johansson
- about Equals and GetHashCode
- Prev by Date: Re: about Equals and GetHashCode
- Next by Date: Re: about Equals and GetHashCode
- Previous by thread: Re: about Equals and GetHashCode
- Next by thread: Re: about Equals and GetHashCode
- Index(es):
Relevant Pages
|