首先直接贴大佬链接看这里
完整直接看大佬就完事了,里面有详细的图解
首先看一下Dictionary的结构体是啥样的
private struct Entry
{
public int hashCode;
//哈希值
// Lower 31 bits of hash code, -1 if unused
public int next;
// Index of next entry, -1 if last
//记录如果哈希值相同的上一个是啥
public TKey key;
//键值
// Key of entry
public TValue value;
//数值
// Value of entry
}
其他变量
private int[] buckets; // Hash桶
//他用来标记这个哈希键值是否被使用,默认是-1,
//被使用后就是那个数据存储的下标,如果有多个相同的就是指向与最后一个
//因为别的相同的都会被最后一个的next一一记录,可以找到所有的相同的
private Entry[] entries; // Entry数组,存放元素
private int count;
// 当前entries的index位置
private KeyCollection keys;
// 存放Key的集合
private ValueCollection values;
// 存放Value的集合
//下面的可以暂时木了解
private int version; // 当前版本,防止迭代过程中集合被更改
private int freeList; // 被删除Entry在entries中的下标index,这个位置是空闲的
private int freeCount; // 有多少个被删除的Entry,有多少个空闲的位置
private IEqualityComparer<TKey> comparer; // 比较器
构造函数
private void Initialize(int capacity)
{
int prime = HashHelpers.GetPrime(capacity);
this.buckets = new int[prime];
for (int i = 0; i < this.buckets.Length; i++)
{
this.buckets[i] = -1;
}
this.entries = new Entry<TKey, TValue>[prime];
this.freeList = -1;
}
添加元素:
假设我们创建的时候分配7个空间空间
Dictionary<int, string> test = new Dictionary<int, string>(7);
现在加入<11,“yingying”>
那么就会计算哈希值 h = 11/7=4;
//记录他的上一个元素
next = buckets[h]
//记录当前元素
buckets[h] = count;
//填入数据
entries[count] = <11,“yingying”>
删除元素:
删除元素好说就是求哈希,然后再buckets找到下标,遍历整个哈希值找到他删除就完事了
。。。
最后贴出原稿,真的是个大佬
大佬帅帅帅