学习C# 哈希表(HashTable)用法

学习C# 哈希表(HashTable)用法

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(); //移除所有元素
  }
}

当获取哈希表中数据时,如果类型声明的不对,会出现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. 对哈希表进行排序

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。

7. HashTable、HashSet和Dictionary的区别

(1). HashTable

哈希表(HashTable)表示键/值对的集合。在.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,用于处理和表现类似key-value的键值对,其中key通常可用来快速查找,同时key是区分大小写;value用于存储对应于key的值。Hashtable中key-value键值对均为object类型,所以Hashtable可以支持任何类型的keyvalue键值对,任何非 null 对象都可以用作键或值。
在哈希表中添加一个key/键值对:HashtableObject.Add(key,); 

扫描二维码关注公众号,回复: 8629570 查看本文章

(2). HashSet

HashSet 类主要是设计用来做高性能集运算的,例如对两个集合求交集、并集、差集等。集合中包含一组不重复出现且无特性顺序的元素,HashSet拒绝接受重复的对象。
HashSet 的一些特性如下:

  • a. HashSet 中的值不能重复且没有顺序。
  • b. HashSet 的容量会按需自动添加。

    (3). Dictionary

    Dictionary表示键和值的集合。Dictionary<string, string>是一个泛型,他本身有集合的功能有时候可以把它看成数组,他的结构是这样的:Dictionary<[key], [value]>,的特点是存入对象是需要与[key]值一一对应的存入该泛型,通过某一个一定的[key]去找到对应的值.

    (4).HashTable和Dictionary的区别:

      - a. HashTable不支持泛型,而Dictionary支持泛型。
      - b. Hashtable 的元素属于 Object 类型,所以在存储或检索值类型时通常发生装箱和拆箱的操作,所以你可能需要进行一些类型转换的操作,而且对于int,float这些值类型还需要进行装箱等操作,非常耗时。
      - c. 单线程程序中推荐使用 Dictionary, 有泛型优势, 且读取速度较快, 容量利用更充分。多线程程序中推荐使用 Hashtable, 默认的 Hashtable 允许单线程写入, 多线程读取, 对 Hashtable 进一步调用 Synchronized() 方法可以获得完全线程安全的类型. 而 Dictionary 非线程安全, 必须人为使用 lock 语句进行保护, 效率大减。
      - d. 在通过代码测试的时候发现key是整数型Dictionary的效率比Hashtable快,如果key是字符串型,Dictionary的效率没有Hashtable快。
static void IntMethod()
{
    int count = 1000000;
    Dictionary<int, int> dictionary = new Dictionary<int, int>();
    Hashtable hashtable = new Hashtable();
    for (int i = 0; i < count; i++)
    {
        dictionary.Add(i,i);
        hashtable.Add(i,i);
    }

    Stopwatch stopwatch = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        int value = dictionary[i];
    }
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);

    stopwatch = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        object value = hashtable[i];
    }
    stopwatch.Stop();

    Console.WriteLine(stopwatch.ElapsedMilliseconds);

}

static void MethodString()
{
    int count = 1000000;
    Dictionary<string, string> dictionary = new Dictionary<string, string>();
    Hashtable hashtable=new Hashtable();
    for (int i = 0; i < count; i++)
    {
        dictionary.Add(i.ToString(),"aaa");
        hashtable.Add(i.ToString(),"aaa");
    }

    Stopwatch stopwatch = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        string value=dictionary[i.ToString()];
    }
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);

    stopwatch = Stopwatch.StartNew();
    for (int i = 0; i < count; i++)
    {
        object value = hashtable[i.ToString()];
    }
    stopwatch.Stop();

    Console.WriteLine(stopwatch.ElapsedMilliseconds);
}

猜你喜欢

转载自www.cnblogs.com/AlexanderZhao/p/12199395.html