簡體   English   中英

HashSet不會刪除具有覆蓋的相等的重復項

[英]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添加了EqualsGetHashCode方法,我知道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 ,則在插入第二PairHashSet將看到哈希碼已經存在,並驗證與共享相同哈希碼的其他對象是否相等。

只需刪除:* 397

如果它們被視為重復項,則必須從GetHashCode()返回相同的int (但是,如果不將它們視為重復項,則仍允許它們返回相同的int,這只會影響性能)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM