I have an immutable class whose only field is a bool[]
(size determined at runtime).
How can I compute a good hash code of this class? Generally I would just call GetHashCode()
on each field, and combine them with one of these operators: + | &
, but since the only possible hash codes are 0
for false
and 1
for true
, that's not really going to get me anywhere. My implementation needs to work with only bools
, and must work for an arbitrary-sized array.
(Probably doesn't matter much, but I'm coding in C#/.NET.)
The GetHashCode method provides this hash code for algorithms that need quick checks of object equality. Syntax: public virtual int GetHashCode (); Return Value: This method returns a 32-bit signed integer hash code for the current object.
When two different objects have the same key, we call that a collision. When we add two Key/Value pairs with the same hashcode to a dictionary, they are both stored in the same bucket. So when we want to retrieve a Value, the GetHashCode method is called on our Key to locate the bucket.
For example, the implementation of the GetHashCode() method provided by the String class returns identical hash codes for identical string values. Therefore, two String objects return the same hash code if they represent the same string value.
GetHashCode() method is used to get the hash code of the specified string. When you apply this method to the string this method will return a 32-bit signed integer hash code of the given string. Syntax: public override int GetHashCode ();
Assuming your bool[]
is named bools
:
unchecked {
int hash = 17;
for(int index = 0; index < bools.Length; index++) {
hash = hash * 23 + bools[index].GetHashCode();
}
return hash;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With