Why is the xor operator used to calculate the hash code?

In this MSDN article http://msdn.microsoft.com/en-us/library/ms132123.aspx he discusses the Equalitycomparer class and has an example. In this example about comparing boxes, it has this class -

class BoxSameDimensions : EqualityComparer<Box>
{
    public override bool Equals(Box b1, Box b2)
    {
        if (b1.Height == b2.Height & b1.Length == b2.Length
            & b1.Width == b2.Width)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public override int GetHashCode(Box bx)
    {
        int hCode = bx.Height ^ bx.Length ^ bx.Width;
        return hCode.GetHashCode();
    }
}

I do not understand the line int hCode = bx.Height ^ bx.Length ^ bx.Width;

Can someone please explain? Why xor?

+4
source share
2 answers

An operator ^is a bitwise exception or operator .

In this case, it is used as a convenient way to generate a hash code from three integers. (I do not think this is a very good way, but this is another problem ...)

, - GetHashCode(), int, int, .

:

public override int GetHashCode(Box bx)
{
    return bx.Height ^ bx.Length ^ bx.Width;
}

SO , XOR : XOR java hashCode(), ?

. , xor - , :

a ^ b ^ a == b

, ints, -, , - - , int.

, ints, :

a ^ a == 0

, ints, , , - .

+5

, , , GetHashCode() - , , (, , + ). (AND, OR, NOT, XOR) XOR ( OR, AND XOR). : System.Object.GetHashCode?. (-, ).

0

All Articles