1

Here is my test code (Contains is not returning true when it should be):

HashSet<TilePosition> test = new HashSet<TilePosition>(new TilePositionCompare());
test.Add(new TilePosition(10,10));

if (test.Contains(new TilePosition(10,10)))
Debug.Log("We should see this");

My Compare Class: using System.Collections.Generic;

public class TilePositionCompare : IEqualityComparer<TilePosition>
{
    public bool Equals(TilePosition tileA, TilePosition tileB)
    {
        return tileA.PosX == tileB.PosX && tileA.PosY == tileB.PosY;
    }

    public int GetHashCode(TilePosition tile)
    {
        return tile.GetHashCode();
    }
}

Here is the class I want to compare:

using System.Collections;
public class TilePosition
{
int posX;
int posY;

public TilePosition (int posX, int posY)
{
    this.posX = posX;
    this.posY = posY;
}
}

I'm not sure where I am going wrong. I've followed some tutorials that appear to do the same thing.

katneps
  • 41
  • 3
  • You seem to be using properties PosX and PosY in the Equals method, where are they in your class? – HasaniH Jan 10 '14 at 23:00

1 Answers1

4

The GetHashCode() should be based upon X/Y.

public class TilePositionCompare : IEqualityComparer<TilePosition>
{
    public bool Equals(TilePosition tileA, TilePosition tileB)
    {
        return tileA.PosX == tileB.PosX && tileA.PosY == tileB.PosY;
    }

    public int GetHashCode(TilePosition tile)
    {
        var hash = 17;
        hash = hash * 23 + tile.PosX.GetHashCode();
        hash = hash * 23 + tile.PosY.GetHashCode();
        return hash;
    }
}

Example adopted from https://stackoverflow.com/a/263416/70386

To know why a odd prime number is used (17), read here: Why does Java's hashCode() in String use 31 as a multiplier?

Community
  • 1
  • 1
jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • 1
    More generally, if `Equals(x, y)` is true for any two objects *x* and *y*, then a correct implementation of `GetHashCode` *must* ensure that `GetHashCode(x)==GetHashCode(y)`. Failure to meet this requirement is the true cause of the "wrong result" reported by the original question. – Sam Harwell Jan 10 '14 at 22:59