Hashtable 用法(三 )

表示键/值对的集合,这些键/值对根据键的哈希代码进行组织。  
   
  每个元素是一个存储在   DictionaryEntry   对象中的键/值对。键不能为空引用(Visual   Basic   中为   Nothing),但值可以。  
   
  用作   Hashtable   中的键的对象必须实现或继承   Object.GetHashCode   和   Object.Equals   方法。如果键相等性只是引用相等性,这些方法的继承实现将满足需要。此外,如果该键存在于   Hashtable   中,那么当使用相同参数调用这些方法时,这些方法必须生成相同的结果。只要键对象用作   Hashtable   中的键,它们就必须是永远不变的。  
   
  当把某个元素添加到   Hashtable   时,将根据键的哈希代码将该元素放入存储桶中。该键的后续查找将使用键的哈希代码只在一个特定存储桶中搜索,这将大大减少为查找一个元素所需的键比较的次数。  
   
  Hashtable   的加载因子确定元素与存储桶的最大比率。加载因子越小,平均查找速度越快,但消耗的内存也增加。默认的加载因子   1.0   通常提供速度和大小之间的最佳平衡。当创建   Hashtable   时,也可以指定其他加载因子。  
   
  当向   Hashtable   添加元素时,Hashtable   的实际加载因子将增加。当实际加载因子达到此加载因子时,Hashtable   中存储桶的数目自动增加到大于当前   Hashtable   存储桶数两倍的最小质数。  
   
  Hashtable   中的每个键对象必须提供其自己的哈希函数,可通过调用   GetHash   访问该函数。但是,可将任何实现   IHashCodeProvider   的对象传递到   Hashtable   构造函数,而且该哈希函数用于该表中的所有对象。  
   
  [Visual   Basic,   C#]   C#   语言中的   foreach   语句(在   Visual   Basic   中为   for   each)需要集合中每个元素的类型。由于   Hashtable   的每个元素都是一个键/值对,因此元素类型既不是键的类型,也不是值的类型。而是   DictionaryEntry   类型。  
  using   System;  
  using   System.Collections;  
  public   class   SamplesHashtable     {  
   
        public   static   void   Main()     {  
   
              //   Creates   and   initializes   a   new   Hashtable.  
              Hashtable   myHT   =   new   Hashtable();  
              myHT.Add("First",   "Hello");  
              myHT.Add("Second",   "World");  
              myHT.Add("Third",   "!");  
   
              //   Displays   the   properties   and   values   of   the   Hashtable.  
              Console.WriteLine(   "myHT"   );  
              Console.WriteLine(   "     Count:         {0}",   myHT.Count   );  
              Console.WriteLine(   "     Keys   and   Values:"   );  
              PrintKeysAndValues(   myHT   );  
        }  
   
   
        public   static   void   PrintKeysAndValues(   Hashtable   myList   )     {  
              IDictionaryEnumerator   myEnumerator   =   myList.GetEnumerator();  
              Console.WriteLine(   "\t-KEY-\t-VALUE-"   );  
              while   (   myEnumerator.MoveNext()   )  
                    Console.WriteLine("\t{0}:\t{1}",   myEnumerator.Key,   myEnumerator.Value);  
              Console.WriteLine();  
        }  
  }  
  /*    
  This   code   produces   the   following   output.  
   
  myHT  
      Count:         3  
      Keys   and   Values:  
          -KEY-         -VALUE-  
          Third:         !  
          Second:         World  
          First:         Hello  
  */  
posted on 2009-08-12 14:31  遥望大海,云卷云舒  阅读(419)  评论(0编辑  收藏  举报