Re: Generate hash code
- From: "Marc Gravell" <mgravell@xxxxxx>
- Date: Wed, 18 Jan 2006 13:01:18 -0000
The hashcode is not the same as the key; the hashcode is just used to
partition the items (fairly arbitrarily) - so that it can jump to a subset
of the larger list before doing any real work. This is why IEqualityComparer
requests both an equality method and a hash method.
I've never written a hashtable from scratch, but I *believe* it tends to
work something like the following:
* The hashtable has a number of buckets; lets say 20 (although this is often
dynamic based on the amount of data contained)
* When adding items, it gets the hashcode (lets say it return 342545), and
then takes the mod (remainder on division) of this with the bucket count to
choose a bucket (bucket 5 in this case)
* When you query the hashtable, it
1: gets the hashcode of your argument and does the same operation to
pick the bucket to look within
2: scans the contents of this bucket (a much shorter list), possibly
checking Equals, or possibly first checking the hash of each item and then
checking Equals if the hash matched (i.e. something in bucket 5 could have a
hash of 342545, or it could have a hash of 25)
This raises another implementation point:
If 2 instances share a hash-code, it is *not* necessary for them to count as
equal (via Equals)
HOWEVER: if two instances *should* count as equal, then the hash codes
should be identical
Of course, if you use any of the inbuilt primatives (int, string, etc) for
your key you will be pretty safe
Marc
.
- References:
- Generate hash code
- From: mortb
- Re: Generate hash code
- From: Marc Gravell
- Re: Generate hash code
- From: mortb
- Generate hash code
- Prev by Date: Re: Adding references: the details
- Next by Date: Re: config file name
- Previous by thread: Re: Generate hash code
- Next by thread: Re: Generate hash code
- Index(es):
Relevant Pages
|