欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

聊聊C# 中HashTable与Dictionary的区别说明

程序员文章站 2022-07-02 19:14:58
1. 哈希表(hashtable)简述在.net framework中,hashtable是system.collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,其中...

1. 哈希表(hashtable)简述

在.net framework中,hashtable是system.collections命名空间提供的一个容器,用于处理和表现类似keyvalue的键值对,其中key通常可用来快速查找,同时key是区分大小写;value用于存储对应于key的值。hashtable中keyvalue键值对均为object类型,所以hashtable可以支持任何类型的keyvalue键值对.

2. 什么情况下使用哈希表

(1)某些数据会被高频率查询(2)数据量大(3)查询字段包含字符串类型(4)数据类型不唯一

3. 哈希表的使用方法

哈希表需要使用的namespace

using system.collections;
using system.collections.generic;

哈希表的基本操作:

//添加一个keyvalue键值对:
hashtableobject.add(key,value);
//移除某个keyvalue键值对:
hashtableobject.remove(key);
//移除所有元素:      
hashtableobject.clear(); 
// 判断是否包含特定键key:
hashtableobject.contains(key);

控制台程序例子:

using system;
using system.collections; //file使用hashtable时,必须引入这个命名空间
class program
{
 public static void main()
 {
   hashtable ht = new hashtable(); //创建一个hashtable实例
   ht.add("北京", "帝都"); //添加keyvalue键值对
   ht.add("上海", "魔都");
   ht.add("广州", "省会");
   ht.add("深圳", "特区");
   string capital = (string)ht["北京"];
   console.writeline(ht.contains("上海")); //判断哈希表是否包含特定键,其返回值为true或false
   ht.remove("深圳"); //移除一个keyvalue键值对
   ht.clear(); //移除所有元素
 }
}   

哈希表中使用多种数据类型的例子:

using system;
using system.collections;
class program
{
  static hashtable gethashtable()
  {
    hashtable hashtable = new hashtable();
    
    hashtable.add("名字", "小丽");
    hashtable.add("年龄", 22);
    return hashtable;
  }
  static void main()
  {
    hashtable hashtable = gethashtable();
    string name = (string)hashtable["名字"];
    console.writeline(name);
    int age = (int)hashtable["年龄"];
    console.writeline(age);
  }
}

当获取哈希表中数据时,如果类型声明的不对,会出现invalidcastexception错误。使用as-statements可以避免该错误。

using system;
using system.collections;
using system.io;
class program
{
  static void main()
  {
  hashtable hashtable = new hashtable();
  hashtable.add(100, "西安");
  // 能转换成功
  string value = hashtable[100] as string;
  if (value != null)
  {
    console.writeline(value);
  }
  // 转换失败,获取的值为null,但不会抛出错误。
  streamreader reader = hashtable[100] as streamreader;
  if (reader == null)
  {
     console.writeline("西安不是streamreader型");
  }
  // 也可以直接获取object值,再做判断
  object value2 = hashtable[100];
  if (value2 is string)
  {
    console.write("这个是字符串型: ");
    console.writeline(value2);
  }
  }
}

4. 遍历哈希表

遍历哈希表需要用到dictionaryentry object,代码如下:

for(dictionaryentry de in ht) //ht为一个hashtable实例
{
  console.writeline(de.key); //de.key对应于keyvalue键值对key
  console.writeline(de.value); //de.key对应于keyvalue键值对value
}

遍历键

foreach (int key in hashtable.keys)
{
  console.writeline(key);
}

遍历值

foreach (string value in hashtable.values)
{
  console.writeline(value);
}

5. 对哈希表进行排序

对哈希表按key值重新排列的做法:

arraylist akeys=new arraylist(ht.keys); 
akeys.sort(); //按字母顺序进行排序
foreach(string key in akeys)
{
  console.writeline(key + ": " + ht[key]); //排序后输出
}

6. 哈希表的效率

system.collections下的哈希表(hashtable)和system.collections.generic下的字典(dictionary)都可用作lookup table,下面比较一下二者的执行效率。

stopwatch sw = new stopwatch();
hashtable hashtable = new hashtable();
dictionary<string, int> dictionary = new dictionary<string, int>();
int countnum = 1000000;
sw.start();
for (int i = 0; i < countnum; i++)
{
  hashtable.add(i.tostring(), i);
}
sw.stop();
console.writeline(sw.elapsedmilliseconds); //输出: 744
sw.restart();
for (int i = 0; i < countnum; i++)
{
  dictionary.add(i.tostring(), i);
}
sw.stop();
console.writeline(sw.elapsedmilliseconds); //输出: 489
sw.restart();
for (int i = 0; i < countnum; i++)
{
  hashtable.containskey(i.tostring());
}
sw.stop();
console.writeline(sw.elapsedmilliseconds); //输出: 245
sw.restart();
for (int i = 0; i < countnum; i++)
{
  dictionary.containskey(i.tostring());
}
sw.stop();
console.writeline(sw.elapsedmilliseconds); //输出: 192

由此可见,添加数据时hashtable快。频繁调用数据时dictionary快。

结论:

dictionary<k,v>是泛型的,当k或v是值类型时,其速度远远超过hashtable。

补充:c# 哈希表hashtable与字典表dictionary<k,v>的比较。

一、hashtable 和 dictionary <k, v> 类型

1):单线程程序中推荐使用 dictionary, 有泛型优势, 且读取速度较快, 容量利用更充分.

2):多线程程序中推荐使用 hashtable, 默认的 hashtable 允许单线程写入, 多线程读取, 对 hashtable 进一步调用 synchronized()方法可以获得完全线程安全的类型. 而dictionary 非线程安全, 必须人为使用 lock 语句进行保护, 效率大减.

3):dictionary 有按插入顺序排列数据的特性 (注: 但当调用 remove() 删除过节点后顺序被打乱), 因此在需要体现顺序的情境中使用 dictionary 能获得一定方便.

在使用哈希表保存集合元素(一种键/值对)时,首先要根据键自动计算哈希代码,以确定该元素的保存位置,再把元素的值放入相应位置所指向的存储桶中。在查找时,再次通过键所对应的哈希代码到特定存储桶中搜索,这样将大大减少为查找一个元素进行比较的次数。

hashtable中的key/value均为object类型,由包含集合元素的存储桶组成。存储桶是 hashtable中各元素的虚拟子组,与大多数集合中进行的搜索和检索相比,存储桶可令搜索和检索更为便捷。每一存储桶都与一个哈希代码关联,该哈希代码是使用哈希函数生成的并基于该元素的键。hashtable的优点就在于其索引的方式,速度非常快。如果以任意类型键值访问其中元素会快于其他集合,特别是当数据量特别大的时候,效率差别尤其大。

hashtable的应用场合有:做对象缓存,树递归算法的替代,和各种需提升效率的场合。

二、哈希表hashtabl

hastable是哈希表的实现,能根据关键字取关键值,这key的类型是object, value的类型也是object。

在哈希表中添加一个key/value键值对:hashtableobject.add(key,value);

在哈希表中去除某个key/value键值对:hashtableobject.remove(key);

从哈希表中移除所有元素: hashtableobject.clear();

判断哈希表是否包含特定键key: hashtableobject.contains(key);

遍历hashtable对象的两种方法:

由于hashtable每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型,而是dictionaryentry类型。

hashtable示例代码

<pre name="code" class="csharp">code highlighting produced by actipro codehighlighter (freeware)http://www.codehighlighter.com/-->//方法一
foreach (system.collections.dictionaryentry de in myhashtable)
{
  //注意hasttable内存储的默认类型是object,需要进行转换才可以输出
  console.writeline(de.key.tostring());
  console.writeline(de.value.tostring());
}
 
 
//方法二
system.collections.idictionaryenumerator enumerator = myhashtable.getenumerator();
 
while (enumerator.movenext())
{
  console.writeline(enumerator.key);    // hashtable关健字
  console.writeline(enumerator.value);   // hashtable值
}

三、字典dictionary

dictionary<tkey,tvalue>是hastbale的泛型实现。

<span style="font-size:18px;">code highlighting produced by actipro codehighlighter (freeware)http://www.codehighlighter.com/-->//遍历键
foreach (string key in mydictionary.keys)
{
  //遍历某键的值
  foreach (string val in mydictionary[key])
  {
 
  }
}</span>

由于 dictionary 是键和值的集合,因此元素类型并非键类型或值类型。相反,元素类型是键类型和值类型的 keyvaluepair 。

<span style="font-size:18px;">字典遍历示例 
 
code highlighting produced by actipro codehighlighter (freeware)http://www.codehighlighter.com/-->foreach (keyvaluepair<string, string> kvp in mydictionary)
{
  string key = kvp.key;//key包含了字典里的键
  for (int i = 0; i < kvp.value.count; i++)
  {
    response.write(kvp.value[i]);
  }
}</span>

示例 :

代码

code highlighting produced by actipro codehighlighter (freeware)http://www.codehighlighter.com/-->//定义一个<string,int>的dictionary,让它的值进行添加(也可以用add方法)
dictionary<string, int> dic = new dictionary<string, int>();
 
//添加两个键为"成绩1","成绩2";并为它们的值赋为0
dic["成绩1"] = 0;
dic["成绩2"] = 0;
 
// 把这两个值分别加1
dic["成绩1"]++;
dic["成绩2"]++;

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。