在大多数编程语言中,字典比哈希表更受欢迎。这背后的原因是什么?
当前回答
在大多数编程语言中,字典优先于哈希表
我认为这不一定是真的,大多数语言都有这两种语言,这取决于他们喜欢的术语。
然而,在C#中,很明显的原因(对我来说)是C#HashTables和System.Collections命名空间的其他成员在很大程度上已经过时了。它们出现在c#V1.1中。它们已从C#2.0替换为System.Collections.Generic命名空间中的Generic类。
其他回答
人们说字典和哈希表是一样的。
这不一定是真的。哈希表是实现字典的一种方法。这是一个典型的例子,它可能是.NET中Dictionary类中的默认例子,但根据定义,它不是唯一的例子。
你同样可以使用链接列表或搜索树来实现字典,但它并没有那么高效(对于一些高效的度量)。
根据我使用.NET Reflector所看到的:
[Serializable, ComVisible(true)]
public abstract class DictionaryBase : IDictionary, ICollection, IEnumerable
{
// Fields
private Hashtable hashtable;
// Methods
protected DictionaryBase();
public void Clear();
.
.
.
}
Take note of these lines
// Fields
private Hashtable hashtable;
因此,我们可以确定DictionaryBase在内部使用HashTable。
因为Dictionary是一个泛型类(Dictionary<TKey,TValue>),所以访问其内容是类型安全的(即,不需要像Hashtable那样从Object转换)。
比较
var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];
to
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;
然而,Dictionary在内部实现为哈希表,因此技术上它的工作方式相同。
集合和泛型对于处理一组对象非常有用。在.NET中,所有集合对象都位于接口IEnumerable下,该接口又具有ArrayList(索引值)和HashTable(键值)。在.NET framework 2.0之后,ArrayList和HashTable被List和Dictionary取代。现在,Arraylist和HashTable在现在的项目中不再使用。
谈到HashTable和Dictionary之间的区别,Dictionary是泛型的,而Hastable不是泛型的。我们可以向HashTable中添加任何类型的对象,但在检索时需要将其转换为所需的类型。因此,它不是类型安全的。但对于字典,在声明自身时,我们可以指定键和值的类型,因此在检索时不需要强制转换。
我们来看一个示例:
散列表
class HashTableProgram
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add(1, "One");
ht.Add(2, "Two");
ht.Add(3, "Three");
foreach (DictionaryEntry de in ht)
{
int Key = (int)de.Key; //Casting
string value = de.Value.ToString(); //Casting
Console.WriteLine(Key + " " + value);
}
}
}
词典
class DictionaryProgram
{
static void Main(string[] args)
{
Dictionary<int, string> dt = new Dictionary<int, string>();
dt.Add(1, "One");
dt.Add(2, "Two");
dt.Add(3, "Three");
foreach (KeyValuePair<int, String> kv in dt)
{
Console.WriteLine(kv.Key + " " + kv.Value);
}
}
}
哈希表:
键/值将在存储到堆中时转换为对象(装箱)类型。
从堆中读取时,需要将键/值转换为所需的类型。
这些操作成本很高。我们需要尽可能避免装箱/拆箱。
字典:HashTable的泛型变体。
禁止装箱/拆箱。无需转换。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- HyperLogLog算法是如何工作的?
- 如何将此foreach代码转换为Parallel.ForEach?