C# 哈希表HashTable的简单使用

本人C#程序菜鸟级别的存在,写博客一方面是为了知识的共享,另一方面也是为了督促自己;大神,可以忽略这篇文文的。废话到此......

哈希表是可以直接进行访问的数据结构,在形式上是类似字典的。不同的是,哈希表内的键值和关键字Key,类型是Object类型的。先说下百度上对哈希表的解释:

哈希表(Hash table,也叫散列表),是根据关键码值(Key value)而直接进行访问的数据结构。也就是说,它通过把关键码值映射到表中一个位置来访问记录,以加快查找的速度。举个栗子:给定表M,存在函数f(key),对任意给定的关键字值key,代入函数后若能得到包含该关键字的记录在表中的地址,则称表M为哈希(Hash)表,函数f(key)为哈希(Hash) 函数。

1.哈希表的简单用法

.NET Framework中,Hashtable是System.Collections命名空间提供的一个容器,所以若文件使用Hashtable时,必须引入命名空间using System.Collections;  

2.哈希表的基本操作[key代表键,value代表值]

添加一个键值对:   HashtableObject.Add(key,value);
移除某个键值对:   HashtableObject.Remove(key);
移除所有元素:       HashtableObject.Clear();
判断是否包含特定键:HashtableObject.Contains(key); 
创建哈希表实例: HashTable  ht = new Hashtable();

获取哈希表长度:实例.Count();

3.哈希表需要注意的简单点

当获取哈希表中数据时,如果类型声明的不对,会出现InvalidCastException错误:使用as语句避免错误;转换失败的情况,获取的值为NULL,但不会抛出错误。为防止转换不正确,也可以直接获取其object值,再做处理

4.遍历哈希表 需要用到DictionaryEntry Object;

栗子代码:

  1 using System;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System.Diagnostics;
  5 using UnityEngine;
  6 
  7 public class myHashTable : MonoBehaviour
  8 {
  9     private Hashtable ht;   
 10     void Start()
 11     {
 12         ht = new Hashtable(); //创建一个Hashtable实例
 13         ht.Add("1", "Beijing");
 14         ht.Add("2", "Shanghai");
 15         ht.Add("3", "Chongqin");
 16         ht.Add("4", 2); //使用多种数据类型
 17                         //Debug.LogError((string)ht["1"]);
 18                         // Debug.LogError(ht.Contains("4"));
 19                         //ht.Remove("4");
 20                         //ht.Clear();
 21                         // Debug.LogError(ht.Contains("2")) ;
 22                         //string a = ht["4"] as string;
 23                         //if (a == null)
 24                         //    Debug.Log("a is null");
 25                         //Debug.Log(a);
 26                          foreach(DictionaryEntry de in ht)
 27                          {
 28                              Debug.Log(de.Key);  //de.Key对应于keyvalue键值对key
 29                              Debug.Log(de.Value);  //de.Key对应于keyvalue键值对value
 30                          }      
 31 
 32         //遍历键   
 33          foreach (string key in ht.Keys)
 34           {
 35               Debug.Log(key);//注意是String类型
 36           }  
 37            foreach (DictionaryEntry de in ht)
 38             {
 39                 int a =(int) de.Key ;
 40                 Debug.Log(a); 
 41             }     
 42         //遍历值 需要值是同一类型,否则报错:InvalidCastException: Cannot cast from source type to destination type. 
 43         
 44          foreach (string value in ht.Values)
 45          {
 46              Debug.Log(value);
 47          }     
 48          ArrayList ak = new ArrayList(ht.Keys);
 49          ak.Sort();
 50          foreach (string a in ak)
 51          {
 52              Debug.Log(a,ht["a"] as UnityEngine.Object);
 53          }
 54           
 55         
 56     }
 57 
 58     private void Awake()
 59     {
 60         Stopwatch sw = new Stopwatch();
 61         List<int> a = new List<int>();
 62         sw.Start();
 63         for (int i = 0; i < 1000000; i++)
 64         {
 65             a.Add(i);
 66         }
 67         sw.Stop();
 68         UnityEngine.Debug.Log(sw.ElapsedMilliseconds);//若循环次数较小,不建议使用sw.Elapsed,因为值可能就是0  
 69 
 70 
 71         
 72         Stopwatch sw = new Stopwatch();
 73         Hashtable hashtable = new Hashtable();
 74         Dictionary<string, int> dictionary = new Dictionary<string, int>();
 75         int countNum = 1000000;
 76 
 77         sw.Start();
 78         for (int i = 0; i < countNum; i++)
 79         {
 80             hashtable.Add(i.ToString(), i);
 81         }
 82         sw.Stop(); 
 84         UnityEngine.Debug.Log(sw.ElapsedMilliseconds);//692
 85         sw.Start();
 86         for (int i = 0; i < countNum; i++)
 87         {
 88             dictionary.Add(i.ToString(), i);
 89         }
 90         sw.Stop(); 
 92         UnityEngine.Debug.Log(sw.ElapsedMilliseconds);//1262
 93         sw.Start(); 
 95             foreach (var i in hashtable)
 96             {
 97             hashtable.ContainsKey(i.ToString());
 98         }
 99         sw.Stop();
100         
101         UnityEngine.Debug.Log(sw.ElapsedMilliseconds);//1723
102         sw.Start(); 
104        foreach(var i in dictionary)
105         {
106             dictionary.ContainsKey(i.ToString());
107         }
108         sw.Stop(); 
109         UnityEngine.Debug.Log(sw.ElapsedMilliseconds);//2230    
110     }
111 
112  
113 }

  由上边的Awake函数内部运行的结果来看,Int型的数据,在添加的时候,字典是较快的;读取时,哈希表很快;不过之前有看到过其他人写的文章,说是string,Object类型的,它们在字典和哈希表的存取速度的比较,有兴趣的可以找找看下。

本人第一次写博客,难免有不足之处,希望大家批评指正,共同进步。

不积跬步,无以至千里;不积小流,无以成江海。
原文地址:https://www.cnblogs.com/allyh/p/8988309.html