2013-02-10 46 views
3

我有HahSet int [9]數組的集合,並且想知道HashSe是否已經包含該數組。 例如如何實現自己的HashSet包含方法

 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?

回答

5

您需要提供的IEqualityComparer<int[]>的實現,並用它把你的自定義比較構造函數:

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

你必須實現自己的陣列相等比較,如一個上市here

然後它的那樣簡單詢問散列設置爲使用比較器:

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