Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetHashCode() from booleans only

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.)

like image 787
Hank Avatar asked Jul 26 '11 15:07

Hank


People also ask

What is GetHashCode method?

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 GetHashCode is called?

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.

How is GetHashCode implemented?

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.

How HashCode is generated in c#?

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 ();


1 Answers

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;
}
like image 54
jason Avatar answered Sep 28 '22 15:09

jason