【问题标题】:How implement own HashSet contains method如何实现自己的 HashSet contains 方法
【发布时间】:2013-02-10 15:14:30
【问题描述】:

我有 int[9] 数组的 HahSet 集合,想知道 HashSe 是否已经包含该数组。 例如

       HashSet<int[]> set = new HashSet<int[]>();
       int[] a=new int[9]{1,2,3,4,5,6,7,8,9};
       set.Add(a);
       int[] a2=new int[9]{1,2,3,4,5,6,7,8,9};
       if(!set.Contains(a2))
          set.Add(a2);

如何重写或实现自己的 Equals 方法,以便 HastSet.Contains 的行为类似于 Arrays.SequenceEquals?

【问题讨论】:

    标签: c#


    【解决方案1】:

    您需要提供IEqualityComparer&lt;int[]&gt; 的实现,并使用带有自定义比较器的构造函数:

    class MyEqCmpForInt : IEqualityComparer<int[]> {
        public bool Equals(int[] a, int[] b) {
            ...
        }
        public int GetHashCode(int[] data) {
            ...
        }
    }
    
    HashSet<int[]> set = new HashSet<int[]>(new MyEqCmpForInt());
    

    【讨论】:

      【解决方案2】:

      哈希集类有a constructor that takes an equality comparer。使用它。

      【讨论】:

        【解决方案3】:

        您必须实现自己的数组相等比较器,例如列出的here。

        然后它就像要求哈希集使用您的比较器一样简单:

        var set = new HashSet<int[]>(new ArrayEqualityComparer<int>());
        ...
            // You don't need to do a Contains check; it's implicit.
        set.Add(someArray);
        

        【讨论】:

          猜你喜欢
          • 2015-10-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-13
          • 2012-10-31
          • 2015-11-11
          • 1970-01-01
          • 2017-01-16
          相关资源
          最近更新 更多