zoukankan      html  css  js  c++  java
  • C#中哈希表(HashTable)的用法详解

    描述: 哈希表存放 key、values ,key值可以用于快速调取用,values 对应object类型,也就是说所有类型。

    实例:

    1.HashTable存放学生的成绩

       Hashtable ht1 = new Hashtable(); //创建一个Hashtable实例
                ht1.Add("张三", "100"); //添加keyvalue键值对
                ht1.Add("李四", "100");
                ht1.Add("王五", "100");
                ht1.Add("赵六", "200");
                string capital1 = (string)ht["王五"];//根据Key值获取信息
                ht.Remove("赵六"); //移除一个keyvalue键值对 ht.Clear(); //移除所有元素
                object value2 = ht["赵六"];//直接根据key取值,判断类型在进行转化
                if (value2 is string)
                {
    
                }
                foreach (DictionaryEntry de in ht) //ht为一个Hashtable实例,遍历哈希表 object对象
                {
                    Control cc = (Control)de.Value;  
                }
                //添加数据时Hashtable快。频繁调用数据时Dictionary快。

    2.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

    Dictionary<K,V>是泛型的,当K或V是值类型时,其速度远远超过Hashtable。

    
    
     
  • 相关阅读:
    JSON格式
    多行写入
    文件对象write() and read()
    一个虚拟摄像头Filter(Virtual Cam Capture Filter)
    五十种最好的开源爬虫
    web scraper 里的 Element click 模拟点击「加载更多」
    介绍一款好用又易学的爬虫工具:web scraper
    安装宝塔面板后 ,centos系统 挂载硬盘 或者 数据盘和系统盘合并
    帝国CMS恢复搜索功能 增加搜索数据源设置教程
    安装帝国CMS步骤 和恢复数据
  • 原文地址:https://www.cnblogs.com/hanke123/p/9996442.html
Copyright © 2011-2022 走看看