Junior — Middle
What data structure is stored in a Map object when implementing key-value mapping?
sobes.tech AI
Answer from AI
In C#, the Map object is usually associated with the Dictionary<TKey, TValue> class, which implements a key-value mapping.
Internally, Dictionary uses a data structure based on a hash table. The main components of this structure are:
- Buckets array — an array of indices pointing to the start of chains of elements with the same hash.
- Entries array — stores key-value pairs along with the hash code and a link to the next element in the chain (for collision resolution).
When adding an element, the hash code of the key is computed, then the bucket index is determined. If the bucket already contains elements with the same hash, a chain (linked list) is used to store multiple elements.
Thus, the data structure is a hash table with chaining to resolve collisions, providing fast access by key.
Example of using Dictionary:
var map = new Dictionary<string, int>();
map["apple"] = 5;
int value = map["apple"]; // value == 5