Skip to content

35. Class System.Collections.Hashtable

February 13, 2011

Dictionaries contain elements, each one identifiable by a key(which can be of any type). A dictionary is made up of two elements: a key and a value.
The advantage of dictionaries compared to lists is to directly access elements based on the key and not based on the index.

Each addition to a dictionary is made up of a value and its associated key. The method Add raises an ArgumentException when an attempt is made to add a duplicate key.
The retrieval of a value based on a key is very fast, because the Dictionary classes are implemented as hash tables.
The concept of a hash table is to calculate, with a given algorithm, a whole hash value, based on the key: it can happen that two different keys have the same whole hash value(phenomena of collision); to solve this problem, the concept of hash table introduces the concept of the basket. A basket contains all couples of key/values having the same hash value(inside the implementation of the hash table).
The dictionaries are implemented by the class Hashtable, in the namespace System.Collections.

 Declaration/instanciation of variable of type hashtable

The class Hashtable implements the interfaces IDictionary, ICollection and IEnumerable.
The size of the dictionary is automatically incremented, decremented(property Count) when inserting or removing an element.
Example: Insert an object of type Person in the dictionary:

Insert person object in dictionary

Example: Iterate through the dictionary with the instruction foreach:

Cycle through dictionary with instruction foreach

The class Hashtable implements other methods, such as:

  • bool ContainsValue(object value)
    Determines whether the Dictionary contains a specific value

Happy Programing! =)

From → OOP

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: