473,467 Members | 1,592 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

string.GetHashCode() and HashTable calls GetHashCode() Differ?

-----See below code,
string str = "blair";
string strValue = "ABC";
string str1 = "brainlessness";
string strValue1 = "XYZ";
int hash = str.GetHashCode() ; // Returns 175803953
int hash1 = str1.GetHashCode(); // Returns 175803953
Hashtable ht = new Hashtable();
ht.Add(hash ,strValue);
ht.Add(hash1,strValue1); // ****ERROR****
string strTmp = (string) ht[str];
string strTmp1 = (string) ht[hash1];

In Above code when i try to call GetHashCode() for both str and str1,
it returns me same Hash Code '175803953', and that's why when i try to
add into hashtable, exception generates which is normal (i know we
cannot add same key twice). Now.... see below code
string str = "blair";
string strValue = "ABC";
string str1 = "brainlessness";
string strValue1 = "XYZ";
Hashtable ht = new Hashtable();
ht.Add(str,strValue);
ht.Add(str1,strValue1);

the above code runs perfectly without any error, so now here i want to
understand one thing, as HashTable calls GetHashCode() method to get
the Hash Code of passed key and as we show in the 1st example that the
both strings are generating the same Hash Code so why there is no
exception in the 2nd example,

Does HashTable use some other algorithm to generate the Hash Code of
passed key? if so, i think then its always better to assign object
directly as a key in stand of first generate the Hash Code and then
assign it to HashTable as a key.

(My main concentration on String as a Key)

Please help me to understand...
Dec 24 '07 #1
8 5848
On Sun, 23 Dec 2007 23:39:40 -0800, Ashish Khandelwal
<AK***************@gmail.comwrote:
[...]
Does HashTable use some other algorithm to generate the Hash Code of
passed key? if so, i think then its always better to assign object
directly as a key in stand of first generate the Hash Code and then
assign it to HashTable as a key.
You are not allowed to have duplicate _keys_ in a Hashtable, but no such
requirement is made on the hash value itself.

The Hashtable (and similar collections) use GetHashCode() to provide fast
access to keys in the Hashtable, but collisions are allowed (they have to
be, otherwise the Hashtable would be artificially restricted in size
according to however large the actual hashed value it winds up using to
index the collection elements). Duplication is detected via the comparer
being used for the Hashtable (e.g. the default comparer would use the
IComparable interface implemented by the data type of the key), not the
hash code itself.

Collisions in the hash value slow things down (a very tiny amount), but
they don't prevent keys that are actually different from being added to
the Hashtable.

In your first example, you are using the hash code itself as a key. Since
keys can't be duplicated, the hash code collision prevents the addition of
the value for that key a second time. The Hashtable doesn't know or care
where you got that int...all it knows is that you tried to use the same
int twice.

In the second example, the string instance itself is the key. Since the
strings are in fact different, you can add each as a key for the
Hashtable. Accessing one of them will be slightly slower than the other
because their hash codes are identical, but otherwise there's no problem.

Pete
Dec 24 '07 #2

"Ashish Khandelwal" <AK***************@gmail.comwrote in message
news:20**********************************@s19g2000 prg.googlegroups.com...
-----See below code,
string str = "blair";
string strValue = "ABC";
string str1 = "brainlessness";
string strValue1 = "XYZ";
int hash = str.GetHashCode() ; // Returns 175803953
int hash1 = str1.GetHashCode(); // Returns 175803953
Hashtable ht = new Hashtable();
ht.Add(hash ,strValue);
ht.Add(hash1,strValue1); // ****ERROR****
string strTmp = (string) ht[str];
string strTmp1 = (string) ht[hash1];

In Above code when i try to call GetHashCode() for both str and str1,
it returns me same Hash Code '175803953', and that's why when i try to
add into hashtable, exception generates which is normal (i know we
cannot add same key twice). Now.... see below code
string str = "blair";
string strValue = "ABC";
string str1 = "brainlessness";
string strValue1 = "XYZ";
Hashtable ht = new Hashtable();
ht.Add(str,strValue);
ht.Add(str1,strValue1);

the above code runs perfectly without any error, so now here i want to
understand one thing, as HashTable calls GetHashCode() method to get
the Hash Code of passed key and as we show in the 1st example that the
both strings are generating the same Hash Code so why there is no
exception in the 2nd example,

Does HashTable use some other algorithm to generate the Hash Code of
passed key? if so, i think then its always better to assign object
directly as a key in stand of first generate the Hash Code and then
assign it to HashTable as a key.

(My main concentration on String as a Key)

In your first example you are adding two KEYS that are identical, but in
the second example you are adding two different keys withe the same
hashvalue. The first is illegal, but the second is not. When you add to a
hashtable a second key that has the same hash as an existing one, you get
what is called a "collission", and the hashtable code provides an algorithm
to solve the collissions (which will assign a different slot in the
hashtable to the second key). You do want to minimize the number of
collissions, since they reduce the performance of the hashtable, and one way
to do it is to have a good hashing algorithm that distributes the hashcodes
evenly along their range of values.
Dec 24 '07 #3

Let me clear my doubt once again

As above given 2 strings are generating the same Hash Code, so when
Hash Table call the GetHashCode() method of passed keys, it will also
get the same Hash Code for both the strings, right?
so now here how it works, it is having 2 keys with same hash code, i
think you are saying that if this will be the case, Hash Code will use
comparer to find out the right value, in short if there is any
delicacy in the Hash Code (inside HashTable) hashtable is capable to
handle the case.

One more thing, As per MSDN, it is not sure that the Default
GetHashCode() (HashTable uses the same) method will always return the
same Hash Code for same object or String so in this case how Hashtable
works how it finds the right value, is there also possibility in
Hashtable to return the wrong value as the GetHashCode() method is now
returning the different Hash Code for same key?
Dec 24 '07 #4
Ashish Khandelwal <AK***************@gmail.comwrote:

<snip>
the above code runs perfectly without any error, so now here i want to
understand one thing, as HashTable calls GetHashCode() method to get
the Hash Code of passed key and as we show in the 1st example that the
both strings are generating the same Hash Code so why there is no
exception in the 2nd example
The keys aren't the same. The hashtable doesn't *just* use the hash
code - it uses the hash code *and* the key. The hash code is a way of
very quickly finding all the *possible* matching keys when fetching
from the table - it then looks through all of those keys and compares
them with the key you're looking up with Equals().

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Dec 24 '07 #5
Oooppps... Typing mistake

Delicacy = Duplicate
The default implementation of the GetHashCode method does not
guarantee unique return values for different objects. 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. Consequently, the
default implementation of this method must not be used as a unique
object identifier for hashing purposes.
For detail please see http://msdn2.microsoft.com/en-us/lib...thashcode.aspx

Dec 24 '07 #6
Thanks a Lot Peter, its making sense to me..

One more question:
Can you able to say me that what is the reason that hash Code can
not be Unique for different Objects?

Dec 24 '07 #7
* * Can you able to say me that what is the reason that hash Code can
not be Unique for different Objects?
Very simple; it is an integer, and has only 2^32 possible values. Now
imagine (as a simple case) that your object is a "long" (Int64)... now
keep incrementing "i" (Int64) and get the hash-code; *eventually* you
are going to see duplicates, simply because you have run out of unused
Int32 values.

The same is true of any data type where there are more than 2^32
feasible values.

As such, hash-tables only use the hash-code to group things; they
don't enforce uniqueness on the hash-code. Two different objects can
return the same hash-code, but two objects that should be *considered*
equal *must* report the same hash-code.

Finally, the following is a perfectly legal (albeit stupid) hash-code
routine:

public override int GetHashCode() {
return 17;
}

Marc
Dec 24 '07 #8

Thanks a lot...

I got really good responses and very satisfy with the answers i got
Dec 24 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Bill Mittenzwey | last post by:
Ok, I've read in the docs, some books and some articles by prominant dotneters about how to override GetHashCode, but it still leaves me somewhat puzzled. I have a custom object which I want to...
4
by: Greg Bacchus | last post by:
Hi, I'm just concerned about storing a large amount of items in a Hashtable. It seems to me that as the number of keys in the Hashtable increases, so does the chance of key clashes. Does anyone...
3
by: cmrchs | last post by:
Hi, why is it requested that when Equals() is implemented in a class that GethashCode() must be implemented as well ? thnx Chris ...
5
by: Stoyan | last post by:
Hi All, I don't understand very well this part of MSDN: "Derived classes that override GetHashCode must also override Equals to guarantee that two objects considered equal have the same hash code;...
8
by: Dan | last post by:
Hi, I did a test in C# double x1 = 1.0; double x2 = 5.29980882362664E-315; int h1 = x1.GetHashCode(); int h2 = x2.GetHashCode(); It turned out that both h1 and h2 = 1072693248
2
by: One Handed Man [ OHM# ] | last post by:
The help for the .NET Framework Class Library tells us that the Object.GetHashCode() Method does not guarantee uniqueness' or consistency and that overriding this and the Equals method is a good...
6
by: Mike9900 | last post by:
Hello, I am wondering why GetHashCode() for the string is using two differemt algorithms in .NET Framework 1.1 and 2. This is creating a big problem, because we relied on this hashcode as...
15
by: Ashish Khandelwal | last post by:
As MSDN is not giving us guarantee upon uniqueness of Hash Code, so could any one suggest me that how to generate a unique Hash Code for same string always, and generate different-2 Hash Code...
28
by: Tony Johansson | last post by:
Hello! I can't figure out what point it is to use GetHashCode. I know that this GetHashCode is used for obtaining a unique integer value. Can somebody give me an example that prove the...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.