C#不像Java那样直接提供名为“HashMap”的类。但是,它的Dictionary<TKey, TValue>
类提供了等效的功能,并且是进行哈希映射操作的推荐方法。
目录
使用Dictionary<TKey, TValue>
作为哈希映射
Dictionary<TKey, TValue>
提供了一个键值存储,对于插入、删除和检索等常见操作,其平均时间复杂度为O(1)。TKey
指定键的类型,TValue
定义关联值的类型。让我们来探讨它的用法:
创建和填充字典:
// 创建一个字典,用于存储字符串作为键,整数作为值。
Dictionary<string, int> myDictionary = new Dictionary<string, int>();
// 使用Add()添加键值对
myDictionary.Add("apple", 1);
myDictionary.Add("banana", 2);
myDictionary.Add("cherry", 3);
// 或者使用集合初始化语法:
Dictionary<string, int> anotherDictionary = new Dictionary<string, int>()
{
{"grape", 4},
{"orange", 5}
};
访问值:
使用键检索值。TryGetValue()
比直接索引更安全,可以处理键不存在的情况:
int appleCount;
if (myDictionary.TryGetValue("apple", out appleCount))
{
Console.WriteLine($"Apple count: {appleCount}"); // 输出:Apple count: 1
}
else
{
Console.WriteLine("Apple not found.");
}
// 直接访问(如果键不存在则抛出KeyNotFoundException)
try
{
Console.WriteLine($"Banana count: {myDictionary["banana"]}"); // 输出:Banana count: 2
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key not found.");
}
遍历字典:
Console.WriteLine("Dictionary contents:");
foreach (KeyValuePair<string, int> kvp in myDictionary)
{
Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
}
移除元素:
myDictionary.Remove("banana");
检查键是否存在:
if (myDictionary.ContainsKey("cherry"))
{
Console.WriteLine("Cherry exists.");
}
高级用法和注意事项
对于需要线程安全的情况,请考虑使用ConcurrentDictionary<TKey, TValue>
。选择键时,确保它们正确实现了GetHashCode()
和Equals()
方法,以避免冲突并保持哈希映射的效率。理解这些方面对于获得最佳性能至关重要。
结论
C#中的Dictionary<TKey, TValue>
是HashMap的有效等效项,为键值存储提供了卓越的性能。其多功能性,加上线程安全替代方案的可用性,使其成为各种C#应用程序的基本数据结构。