C# doesn’t offer a class directly named “HashMap,” unlike Java. However, its Dictionary<TKey, TValue>
class provides equivalent functionality and is the recommended approach for hash map operations.
Table of Contents
Using Dictionary<TKey, TValue>
as a Hash Map
Dictionary<TKey, TValue>
offers a key-value store with O(1) average time complexity for common operations like insertion, deletion, and retrieval. TKey
specifies the key type, and TValue
defines the associated value type. Let’s explore its usage:
Creating and Populating a Dictionary:
// Create a dictionary to store strings as keys and integers as values.
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
// Add key-value pairs using Add()
myDictionary.Add("apple", 1);
myDictionary.Add("banana", 2);
myDictionary.Add("cherry", 3);
// Or use collection initializer syntax:
Dictionary<string, int> anotherDictionary = new Dictionary<string, int>()
{
{"grape", 4},
{"orange", 5}
};
Accessing Values:
Retrieve values using their keys. TryGetValue()
is safer than direct indexing, handling cases where the key is absent:
int appleCount;
if (myDictionary.TryGetValue("apple", out appleCount))
{
Console.WriteLine($"Apple count: {appleCount}"); // Output: Apple count: 1
}
else
{
Console.WriteLine("Apple not found.");
}
// Direct access (throws KeyNotFoundException if key is missing)
try
{
Console.WriteLine($"Banana count: {myDictionary["banana"]}"); // Output: Banana count: 2
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key not found.");
}
Iterating Through a Dictionary:
Console.WriteLine("Dictionary contents:");
foreach (KeyValuePair<string, int> kvp in myDictionary)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
Removing Elements:
myDictionary.Remove("banana");
Checking for Key Existence:
if (myDictionary.ContainsKey("cherry"))
{
Console.WriteLine("Cherry exists.");
}
Advanced Usage and Considerations
For scenarios requiring thread safety, consider ConcurrentDictionary<TKey, TValue>
. When choosing keys, ensure they implement GetHashCode()
and Equals()
correctly to avoid collisions and maintain hash map efficiency. Understanding these aspects is crucial for optimal performance.
Conclusion
Dictionary<TKey, TValue>
in C# is the effective equivalent of a HashMap, providing excellent performance for key-value storage. Its versatility, combined with the availability of thread-safe alternatives, makes it a fundamental data structure for diverse C# applications.