![](/img/trans.png)
[英]Why when i call the remove operation of this hashset it doesn't use the gethashcode neither the equality implementation?
[英]HashSet doesn't remove dupes with overridden equality
我有一個Pair
類,由於它存儲的兩個值是可互換的,因此需要一個重寫的等式運算符,代碼是這樣的
Pair.cs
public class Pair
{
protected bool Equals(Pair other)
{
return (Equals(A, other.A) && Equals(B, other.B)) || (Equals(A, other.B) && Equals(B, other.A));
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == this.GetType() && Equals((Pair) obj);
}
public override int GetHashCode()
{
unchecked
{
return ((A != null ? A.GetHashCode() : 0)*397) ^ (B != null ? B.GetHashCode() : 0);
}
}
public readonly Collision A, B;
public Pair(Collision a, Collision b)
{
A = a;
B = b;
}
public static bool operator ==(Pair a, Pair b)
{
if (ReferenceEquals(a, b))
return true;
if ((object)a == null || (object)b == null)
return false;
return (a.A == b.A && a.B == b.B) || (a.A == b.B && a.B == b.A);
}
public static bool operator !=(Pair a, Pair b)
{
return !(a == b);
}
}
我讓ReSharper添加了Equals
和GetHashCode
方法,我知道Equals
可以,但是GetHashCode
輸出正確的值嗎?
我有一個用於存儲對的HashSet<Pair>
,我需要確保此列表中沒有重復項,但是當我將對添加到HashSet
它不會刪除重復項。
只是為了澄清,這將是重復的:
Pair a = new Pair(objecta, objectb);
Pair b = new Pair(objectb, objecta);
HashSet<Pair> pairs = new HashSet<Pair>();
pairs.Add(a);
pairs.Add(b);
return pairs.Count(); //Count() returns 2 when it should be 1!
您的GetHashCode
實現不會為(A,B)和(B,A)返回相同的值。 HashSet
在插入時檢查它是否已經包含給定的哈希。 如果不是,則該對象將被視為新對象。
如果您更正了GetHashCode
,則在插入第二Pair
, HashSet
將看到哈希碼已經存在,並驗證與共享相同哈希碼的其他對象是否相等。
只需刪除:* 397
如果它們被視為重復項,則必須從GetHashCode()返回相同的int 。 (但是,如果不將它們視為重復項,則仍允許它們返回相同的int,這只會影響性能)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.