473,770 Members | 1,806 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Own implementation of GetHashCode()

I have a class which should override the GetHashcode() function, which
look like this:

public class A
{
public string str1;
public string str2;

//other methods...

public override int GetHashCode()
{
return ???;
}
}

The instance members str1 and str2 are the "primary keys" of my class.
All instances of A with the same values for str1 and str2 should return
the same hash code. The implementation should be also as fast as possible.

An instance with A.str1 = "x" and A.str2 = "y" should return a different
hashcode as an instance with A.str1 = "y" and A.str2 = "x".

How to implement such a behavior and ensure that my hash code is
consistent? How does the implementation of System.String do this?

Thanks for any help and suggestions.
Matthias
Nov 17 '05 #1
8 9907
There are probably many ways, but this is one of them.

You could concatenate str1 and str2 and then use that hash code, as of the
System.String.G etHashCode implementation.
public override int GetHashCode()
{
return string.Concat(s tr1, str2).GetHashCo de();
}

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Matthias Kientz" <no***********@ funkinform.de> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
I have a class which should override the GetHashcode() function, which look
like this:

public class A
{
public string str1;
public string str2;

//other methods...

public override int GetHashCode()
{
return ???;
}
}

The instance members str1 and str2 are the "primary keys" of my class.
All instances of A with the same values for str1 and str2 should return
the same hash code. The implementation should be also as fast as possible.

An instance with A.str1 = "x" and A.str2 = "y" should return a different
hashcode as an instance with A.str1 = "y" and A.str2 = "x".

How to implement such a behavior and ensure that my hash code is
consistent? How does the implementation of System.String do this?

Thanks for any help and suggestions.
Matthias

Nov 17 '05 #2
There are probably many ways, but this is one of them.

You could concatenate str1 and str2 and then use that hash code, as of the
System.String.G etHashCode implementation.
public override int GetHashCode()
{
return string.Concat(s tr1, str2).GetHashCo de();
}

--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Matthias Kientz" <no***********@ funkinform.de> wrote in message
news:%2******** ********@TK2MSF TNGP09.phx.gbl. ..
I have a class which should override the GetHashcode() function, which look
like this:

public class A
{
public string str1;
public string str2;

//other methods...

public override int GetHashCode()
{
return ???;
}
}

The instance members str1 and str2 are the "primary keys" of my class.
All instances of A with the same values for str1 and str2 should return
the same hash code. The implementation should be also as fast as possible.

An instance with A.str1 = "x" and A.str2 = "y" should return a different
hashcode as an instance with A.str1 = "y" and A.str2 = "x".

How to implement such a behavior and ensure that my hash code is
consistent? How does the implementation of System.String do this?

Thanks for any help and suggestions.
Matthias

Nov 17 '05 #3
Dennis Myrén wrote:
There are probably many ways, but this is one of them.

You could concatenate str1 and str2 and then use that hash code, as of the
System.String.G etHashCode implementation.
public override int GetHashCode()
{
return string.Concat(s tr1, str2).GetHashCo de();
}


This was my first idea, too.

But this will return the same hash code for the following instances:
InstanceA.str1 = "x"; InstanceA.str2 = "yz";
InstanceB.str1 = "xy"; InstanceB.str2 = "z";

The goal is, to find a way to ensure that different values of str1 and
str2 result in a differnt hashcode.
Nov 17 '05 #4
Dennis Myrén wrote:
There are probably many ways, but this is one of them.

You could concatenate str1 and str2 and then use that hash code, as of the
System.String.G etHashCode implementation.
public override int GetHashCode()
{
return string.Concat(s tr1, str2).GetHashCo de();
}


This was my first idea, too.

But this will return the same hash code for the following instances:
InstanceA.str1 = "x"; InstanceA.str2 = "yz";
InstanceB.str1 = "xy"; InstanceB.str2 = "z";

The goal is, to find a way to ensure that different values of str1 and
str2 result in a differnt hashcode.
Nov 17 '05 #5

You can never guarantee that has codes will be unique, but you can use
additional calculations to reduce the chance of duplication. The
following calculates the hash codes individually, performs a bit shift
on one, and then xors them.

Note that GetHashCode should be a fast operation and if the calcuation
is too long, you can reduce the benefit of addtional uniqueness (i.e.,
time it takes to calculate for all values vs. the time it takes to
loop through the buckets for collided values).

HTH,

Sam
using System;

namespace __WinTesterCS
{
public class GetHashCodeTest
{
public static void Test()
{
Strings[] a = new Strings[5];
a[0] = new Strings("a","bc ");
a[1] = new Strings("ab", "c");
a[2] = new Strings("abc"," ");
a[3] = new Strings("","abc ");
a[4] = new Strings(null,"a bc");

for(int i=0; i<a.Length; i++)
{
Console.WriteLi ne(a[i].String1 + " / " + a[i].String2 + " -> "
+ a[i].GetHashCode(). ToString("X"));
}
}
}

public class Strings
{
public string String1;
public string String2;

public Strings(string string1, string string2)
{
String1 = string1;
String2 = string2;
}

public override int GetHashCode()
{
int i1 = String1 != null ? String1.GetHash Code() : 0;
int i2 = String2 != null ? String2.GetHash Code() : 0;
return (i1 >> 1) ^ i2;
}

}

}

B-Line is now hiring one Washington D.C. area VB.NET
developer for WinForms + WebServices position.
Seaking mid to senior level developer. For
information or to apply e-mail resume to
sam_blinex_com.
Nov 17 '05 #6

You can never guarantee that has codes will be unique, but you can use
additional calculations to reduce the chance of duplication. The
following calculates the hash codes individually, performs a bit shift
on one, and then xors them.

Note that GetHashCode should be a fast operation and if the calcuation
is too long, you can reduce the benefit of addtional uniqueness (i.e.,
time it takes to calculate for all values vs. the time it takes to
loop through the buckets for collided values).

HTH,

Sam
using System;

namespace __WinTesterCS
{
public class GetHashCodeTest
{
public static void Test()
{
Strings[] a = new Strings[5];
a[0] = new Strings("a","bc ");
a[1] = new Strings("ab", "c");
a[2] = new Strings("abc"," ");
a[3] = new Strings("","abc ");
a[4] = new Strings(null,"a bc");

for(int i=0; i<a.Length; i++)
{
Console.WriteLi ne(a[i].String1 + " / " + a[i].String2 + " -> "
+ a[i].GetHashCode(). ToString("X"));
}
}
}

public class Strings
{
public string String1;
public string String2;

public Strings(string string1, string string2)
{
String1 = string1;
String2 = string2;
}

public override int GetHashCode()
{
int i1 = String1 != null ? String1.GetHash Code() : 0;
int i2 = String2 != null ? String2.GetHash Code() : 0;
return (i1 >> 1) ^ i2;
}

}

}

B-Line is now hiring one Washington D.C. area VB.NET
developer for WinForms + WebServices position.
Seaking mid to senior level developer. For
information or to apply e-mail resume to
sam_blinex_com.
Nov 17 '05 #7
Samuel R. Neff wrote:
You can never guarantee that has codes will be unique, but you can use
additional calculations to reduce the chance of duplication. The
following calculates the hash codes individually, performs a bit shift
on one, and then xors them.

Note that GetHashCode should be a fast operation and if the calcuation
is too long, you can reduce the benefit of addtional uniqueness (i.e.,
time it takes to calculate for all values vs. the time it takes to
loop through the buckets for collided values).

HTH,

Sam
using System;

namespace __WinTesterCS
{
public class GetHashCodeTest
{
public static void Test()
{
Strings[] a = new Strings[5];
a[0] = new Strings("a","bc ");
a[1] = new Strings("ab", "c");
a[2] = new Strings("abc"," ");
a[3] = new Strings("","abc ");
a[4] = new Strings(null,"a bc");

for(int i=0; i<a.Length; i++)
{
Console.WriteLi ne(a[i].String1 + " / " + a[i].String2 + " -> "
+ a[i].GetHashCode(). ToString("X"));
}
}
}

public class Strings
{
public string String1;
public string String2;

public Strings(string string1, string string2)
{
String1 = string1;
String2 = string2;
}

public override int GetHashCode()
{
int i1 = String1 != null ? String1.GetHash Code() : 0;
int i2 = String2 != null ? String2.GetHash Code() : 0;
return (i1 >> 1) ^ i2;
}

}

}


Hi Samuel,

I've tested your suggestion, but it produces to much collisions for my
purposes (I have many short strings as keys).

My solution is to copy each character of the strings (alternating) to a
buffer, convert this to a string and get the hash code. Because this is
not very fast, I do this in the constructor and save the hash code in
the instance.

public class A
{
protected string str1;
protected string str2;
protected hash;

public A(string s1, string s2)
{
int n1 = s1.Length;
int n2 = s2.Length;
int j = 0;
str1 = s1;
str2 = s2;

// the buffer gets the double length of the largest string
int nLength = n1 > n2 ?
n1 * 2 : n2 * 2;

char[] buffer = new char[nLength];

// copy each char alternating, use spaces to fill the smaller string
for(int i = 0; i < nLength; i++)
{
buffer[i] = j < n1 ? s1[j] : ' ';
i++;
buffer[i] = j < n2 ? s2[j] : ' ';
j++;
}

// convert to string and get the hash code
hash = new String(buffer). GetHashCode();
}

public override int GetHashCode()
{
// use our saved hash code, this is very, very fast now
return hash;
}
}
Nov 17 '05 #8
You could concatenate str1 and str2 and then use that hash code, as of
the
System.String.G etHashCode implementation.
public override int GetHashCode()
{
return string.Concat(s tr1, str2).GetHashCo de();
}


This was my first idea, too.

But this will return the same hash code for the following instances:
InstanceA.str1 = "x"; InstanceA.str2 = "yz";
InstanceB.str1 = "xy"; InstanceB.str2 = "z";

The goal is, to find a way to ensure that different values of str1 and
str2 result in a differnt hashcode.


If you have some knowledge about your strings maybe you can just add an
"unused" divider between
the strings to make them more likely to be unique for any two string pairs

public override int GetHashCode()
{
string DIV = "@"; //or even "@$¤%&098ggj494 "
return string.Concat(s tr1+DIV, str2).GetHashCo de();
}
you can move the calculation to the constructor and return a cached value of
the hashcode as you've
already shown

Martin
Nov 17 '05 #9

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

Similar topics

7
6576
by: Avin Patel | last post by:
Hi I have question for GetHashCode() function, Is it correct in following code or there is more efficient way to implement GetHashCode() function class IntArray public int data public override int GetHashCode() int hash = 0 for (int i = 0; i < data.Length; i++
3
5660
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 ********************************************************************** Sent via Fuzzy Software @ http://www.fuzzysoftware.com/ Comprehensive, categorised, searchable collection of links to ASP & ASP.NET resources...
1
1936
by: Anders Borum | last post by:
Hello! I have a framework where all objects are uniquely identified by a GUID (Global Unique Identifier). The objects are used in conjunction with lots of hashtables and I was thinking, that overriding the GetHashCode base method (inherited from object) was a good idea. public abstract class CmsObjectNode : CmsObject, IXml { private Guid cmsObjectID = Guid.NewGuid();
5
9605
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; otherwise, Hashtable might not work correctly." Does any one know, why we must also override Equals, Please give my an example:) Thanks, Stoyan
0
262
by: Matthias Kientz | last post by:
I have a class which should override the GetHashcode() function, which look like this: public class A { public string str1; public string str2; //other methods...
8
5795
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
5
2285
by: Metaman | last post by:
I'm trying to write a generic method to generate Hashcodes but am having some problems with (generic) collections. Here is the code of my method: public static int GetHashCode(object input) { try { Type objectType = input.GetType(); PropertyInfo properties = objectType.GetProperties();
8
5870
by: Ashish Khandelwal | last post by:
-----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****
28
3789
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 usefulness of this GetHashCode or it it of no use at all? A mean that if I get an integer from current time in some way what should I use it for?
0
9617
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10257
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10037
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9904
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8931
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6710
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4007
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 we have to send another system
3
2849
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.