How the Dictionary is internally maintained?

前端 未结 4 664
广开言路
广开言路 2021-01-17 16:57

When i say

Dictionary

is it equivalent to two different arrays such as:

int[] keys =new int[] { 1, 2, 3          


        
相关标签:
4条回答
  • 2021-01-17 17:17

    No, it's a Hash Table. Well it's not exactly a hash table, but it's really closely related.

    http://en.wikipedia.org/wiki/Hash_table.

    http://www.kirupa.com/net/dictionary_hashtable.htm

    0 讨论(0)
  • 2021-01-17 17:24

    It's all clearly written on MSDN:

    The Dictionary(Of TKey, TValue) generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary(Of TKey, TValue) class is implemented as a hash table.

    0 讨论(0)
  • 2021-01-17 17:27

    That's not too far off. Looking at the source code in Reflector, it seems three internal collections are used:

    private Entry<TKey, TValue>[] entries;
    private KeyCollection<TKey, TValue> keys;
    private ValueCollection<TKey, TValue> values;
    

    Note that there is also a int[] buckets variable to keep track of the buckets required in the case of hash-code collisions.

    These variables' purposes should all be fairly self-explanatory. This is not particularly surprising, anyway, since the Dictionary class is known and documented to provide (ideally, with one item per bucket) O(1) lookup time.

    0 讨论(0)
  • 2021-01-17 17:34

    It is hashtable. For each key Dictionary calculates its hash code, and uses this as a pointer to place where value should reside. If there are two keys matching the same hash code, such situation is called collision and internally for this special case Dictionary uses binary tree.

    Algorithmic complexity of Dictionary(hashtable) is O(1) and in worst case O(log(N)) (worst case means we deal only with collisions), where N is a number of elements in Dictionary.

    0 讨论(0)
提交回复
热议问题