5.1. ISet HashSet

ISet:ICollection

4个实现类
system.dll
1. SortedSet
2. TreeSet
3. TreeSubSet

system.core.dll
4. HashSet

ISet method

new bool Add(T item);

//交差并补
void UnionWith(IEnumerable other); //并集 A UNION B
void IntersectWith(IEnumerable other); //交集 A AND B
void ExceptWith(IEnumerable other);//差集 A NOT B
void SymmetricExceptWith(IEnumerable other);//A NOR B A和B的联集

//包含关系判断
bool IsSubsetOf(IEnumerable other); //set 是否是other的子集,other要大
bool IsProperSupersetOf(IEnumerable other); //set 是否是other的子集,other要大,set!=other

bool IsSupersetOf(IEnumerable other); //确定当前集是否为指定集合的超集。
bool IsProperSubsetOf(IEnumerable other); //确定当前集是否为指定集合的真(严格)子集。

//包含任何相同元素
bool Overlaps(IEnumerable other); //有交集吗

// 完全相等
bool SetEquals(IEnumerable other); //集合元素完全相等

jihe关系

HashSet system.core.dll

内存存储实现几乎Dictionary<TKey,TValue>一样,都是双散列
其实重要的不是不重复,而是hash,而是获取,新增,修改是O(1)

1. int[] m_buckets;
2. Slot[] m_slots; //存value和hashcode
3. m_count

接口继承

ISet,
ICollection,
ISerializable...

保证不重复的秘密

这个其实简单,而且不重要,你用普通数组都可以做到数据不重复,只是每次添加都遍历判断下

而这里hashset只是在dictionary抛出异常的地方选择不抛出异常

method

AddIfNotPresent(T value); //类似Dictionary中的Insert(Tkey,TValue,bool) 只是新增重复的时候没有抛出异常

重点是怎么来实现ISet的呢

并集

public UnionWith(IEnumerable other)
{
foreach(T item in other){AddIfNotPresent(item)};
}

交集

比较复杂,但是好在hashset获取数据是O(1),不需要循环对比,所以只要循环other一遍就可以了,并且为了记录下是否存在,所以需要使用bithelp来定义bit数组,

如果是0,1这种简单的操作是可以使用bit数组来解决内存的 (比如 System.Collections.BitArray mscorlib.dll)

SortedSet

继承

ISet,
ICollection,
ICollection,ISerializable,IDeserializationCallback,IReadOnlyCollection

内部

Node root;
IComparer comparer;
int count;
int version
Object _syncRoot;

ctor

1. SortedSet(){comparer=Comparer.Default;}
2. SortedSet(IComparer){}
3. SortedSet<IEnumerable collection){}
4. SortedSet<IEnumerable collection,IComparer comparer){}

posted @ 2017-10-19 21:40  给我一个理由  阅读(221)  评论(0)    收藏  举报