Baz
Baz

Reputation: 13125

Unique keys in Dictionary for class containing longs

If I want to use objects of this class as keys in a Dictionary, what do I need to do? (10.0, 20.0) shouldn't exist as a key twice.

public class IntPoint
{
    public Int64 X { get; set; }
    public Int64 Y { get; set; }

    public IntPoint(Int64 X, Int64 Y)
    {
        this.X = X; this.Y = Y;
    }

    public override int GetHashCode()
    {
        return X.GetHashCode() ^ Y.GetHashCode();
    }
}

EDIT

public static Dictionary<IntPoint, List<int>> GetPolygonDuplicateIndixes(Polygon p)
{
    Dictionary<IntPoint, List<int>> d = new Dictionary<IntPoint, List<int>>();
    int i = 0;
    foreach(IntPoint point in p)
    {
        if(!d.ContainsKey(point))
        {
            d[point] = new List<int>();
        }
        d[point].Add(i);
        i++;
    }
    ...

I'm getting duplicates in d. Why? 22002, 1501 occurs twice in p.

Upvotes: 3

Views: 401

Answers (3)

Boaz
Boaz

Reputation: 4669

If you look at the Dictionary documentation, you'll see that if the keys implement IEquatable, that equality implementation will be used instead.

Upvotes: 6

Bartosz
Bartosz

Reputation: 3358

Your GetHashCode can look like:

public override int GetHashCode()
{
    return X.GetHashCode() ^ Y.GetHashCode();
}

But you still need to override Equals and implement IEquatable interface.

You may also use Tuple<Int64, Int64> instead of your own IntPoint class (if you're on .NET 4.0).

Upvotes: 2

Mike Goodwin
Mike Goodwin

Reputation: 8880

The following link from MSDN recommends using combining X and Y using an XOR operation

http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx#Y1500

public override int GetHashCode() {
  return X ^ Y;

}

The thing to remember is that

  1. It is important that the hash computation is fast
  2. If two objects are equal then there hash mush be equal, but two objects with the same hash do not necessarily have to be equal

Upvotes: 2

Related Questions