我有以下类:
public class SimplePolygon
{
Point[] pointCollection;
public SimplePolygon(Point[] pointCollection)
{
this.pointCollection = pointCollection;
}
public override int GetHashCode()
{
if (ReferenceEquals(pointCollection, null) || (pointCollection.Count() == 0))
return pointCollection.GetHashCode();
int hash = 17;
for (int i = 0; i < pointCollection.Count(); i++)
hash = hash * 23 + pointCollection[i].GetHashCode();
return hash;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(obj, null))
return false;
if (!(obj is SimplePolygon))
return false;
if (this.pointCollection.Count() != (obj as SimplePolygon).pointCollection.Count())
return false;
for (int i = 0; i < this.pointCollection.Count(); i++)
if (!(obj as SimplePolygon).pointCollection.Contains(this.pointCollection[i]))
return false;
return true;
}
}我的问题是Equals方法和GetHashCode方法不一致:
Point p1, p2, p3, p4;
//...create and initialize p1, p2, p3, p4.
SimplePolygon polygon1 = new SimplePolygon(p1, p2, p3, p4);
SimplePolygon polygon2 = new SimplePolygon(p4, p3, p2, p1);
polygon1 == polygon2; //this is true
polygon1.GetHashCode() == polygon2.GetHashCode(); //this is false这违反了规则,即两个相等的对象应该具有相同的哈希码。
我的问题是,散列代码是从数组的第一个元素到最后一个元素生成的,而Equals方法并不关心数组中点的顺序(对于简单多边形或不相交的多边形,点的顺序是无关的- (p1,p2,p3,p4)与(p2,p3,p4,p1)或(p3,p4,p1,p2)或(p4,p3,p2,p1)相同)
有没有人知道在这种情况下生成哈希码的好方法?
发布于 2011-07-22 20:00:53
变化
for (int i = 0; i < pointCollection.Count(); i++)
hash = hash * 23 + pointCollection[i].GetHashCode(); 例如to
for (int i = 0; i < pointCollection.Count(); i++)
hash += pointCollection[i].GetHashCode(); 所以它不依赖于点的顺序。
发布于 2011-07-22 19:58:32
一种解决方案是,你可以找到一个好的起点。例如,你找到最左边的点,并从那里开始计算你的哈希值。
发布于 2011-07-22 20:02:19
简化你的散列算法。例如:只要返回pointCollection的长度即可。您可能可以从那里对其进行微调。
https://stackoverflow.com/questions/6789589
复制相似问题