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 8 9910
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
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
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.
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.
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.
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.
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;
}
} 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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++
|
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...
|
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();
|
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
|
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...
| |
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
|
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();
|
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****
|
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?
|
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...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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,...
|
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...
|
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
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...
| |