C#的字典Dictionary也是比较常用的数据结构,简单解析一下字典的源码结构:
字典类:
public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary,
IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback
字典内部定义了一个结构体,用来存储数据:
private struct Entry {
public int hashCode; // 哈希值
public int next; // 指向下一个数据,如果没有,就等于-1
public TKey key; // 这个就是存储字典数据的键
public TValue value; // 这个就是存储字典数据的值
}
其余的一些比较重要的字段:
private int[] buckets; //这是一个桶容器
private Entry[] entries; //这是存放数据的容器
private int count; //理解为entries数组里距离数组末尾不为空的数据的下标+1
private int version; //版本号,如果有修改就需要更新
private int freeList; //这个字段代表在count范围内,数据为空的下标
private int freeCount; //这个字段代表在count范围内,数据为空的数量
private KeyCollection keys; //存放所有的Key
private ValueCollection values; //存放所有的Value
//获取字典存储的数据长度
public int Count {
//这里的count可以理解为,entries数组里距离数组末尾不为空的数据的下标+1,
//如果有空槽位,需要再减去空槽位,才是真正的数量
//举个例子
//假如entries数组长度是5,里边存储的数据分别为 0 0 2 0 0
//那么这里的count就是3,这里的 freeCount=2,结果就是3-2=1
//真正存储数据的长度就是1
get { return count - freeCount; }
}
字典的构造函数:
public Dictionary(): this(0, null) {}
public Dictionary(int capacity): this(capacity, null) {}
public Dictionary(IEqualityComparer<TKey> comparer): this(0, comparer) {}
public Dictionary(int capacity, IEqualityComparer<TKey> comparer) {
if (capacity < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (c