blog

枪手亨利

博客园 首页 新随笔 联系 订阅 管理

表示键/值对的集合,这些键/值对根据键的哈希代码进行组织。

有关此类型所有成员的列表,请参阅 Hashtable 成员

System.Object
   System.Collections.Hashtable
      System.Data.PropertyCollection

[Visual Basic]
<Serializable>
Public Class Hashtable
   Implements IDictionary, ICollection, IEnumerable, ISerializable, _
   _
   IDeserializationCallback, ICloneable
[C#]
[Serializable]
public class Hashtable : IDictionary, ICollection, IEnumerable,
   ISerializable, IDeserializationCallback, ICloneable
[C++]
[Serializable]
public __gc class Hashtable : public IDictionary, ICollection,
   IEnumerable, ISerializable, IDeserializationCallback, ICloneable
[JScript]
public
   Serializable
class Hashtable implements IDictionary, ICollection,
   IEnumerable, ISerializable, IDeserializationCallback, ICloneable

线程安全

要支持一个或多个编写器,Hashtable 上的所有操作都必须通过 Synchronized 方法返回的包装执行。

通过集合枚举在本质上不是一个线程安全的过程。甚至在对集合进行同步处理时,其他线程仍可以修改该集合,这会导致枚举数引发异常。若要在枚举过程中保证线程安全,可以在整个枚举过程中锁定集合,或者捕捉由于其他线程进行的更改而引发的异常。

备注

每个元素是一个存储在 DictionaryEntry 对象中的键/值对。键不能为空引用(Visual Basic 中为 Nothing),但值可以。

用作 Hashtable 中的键的对象必须实现或继承 Object.GetHashCodeObject.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 类型。例如:

[C#] 
foreach (DictionaryEntry myDE in myHashtable) {...}
[Visual Basic] 
Dim myDE As DictionaryEntry
For Each myDE In myHashtable
   ...
Next myDE

[Visual Basic, C#] foreach 语句是对枚举数的包装,它只允许从集合中读取,不允许写入集合。

示例

下列示例说明如何创建和初始化 Hashtable,以及如何打印出其键和值。

[Visual Basic] 
Imports System
Imports System.Collections
Imports Microsoft.VisualBasic

Public Class SamplesHashtable    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new Hashtable.
        Dim myHT As 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)
    End Sub
    
    Public Shared Sub PrintKeysAndValues(myList As Hashtable)
        Dim myEnumerator As IDictionaryEnumerator = myList.GetEnumerator()
        Console.WriteLine(ControlChars.Tab + "-KEY-" + ControlChars.Tab _
           + "-VALUE-")
        While myEnumerator.MoveNext()
            Console.WriteLine(ControlChars.Tab + "{0}:" + ControlChars.Tab _
               + "{1}", myEnumerator.Key, myEnumerator.Value)
        End While
        Console.WriteLine()
    End Sub
End Class

' This code produces the following output.
' 
' myHT
'   Count:    3
'   Keys and Values:
'     -KEY-    -VALUE-
'     Third:    !
'     Second:    World
'     First:    Hello 

[C#] 
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
*/ 

[C++] 
#using <mscorlib.dll>
#using <system.dll>

using namespace System;
using namespace System::Collections;

public __gc class SamplesHashtable  {

public:
    static void PrintKeysAndValues(Hashtable __gc *myList ) {
        IDictionaryEnumerator __gc *myEnumerator = myList->GetEnumerator();
        Console::WriteLine(S"\t-KEY-\t-VALUE-");
        while (myEnumerator->MoveNext())
            Console::WriteLine(S"\t{0}:\t{1}", myEnumerator->Key, myEnumerator->Value);
        Console::WriteLine();
    };
};

int main()  {

    // Creates and initializes a new Hashtable.
    Hashtable __gc *myHT = new Hashtable();
    myHT->Add(S"First", S"Hello");
    myHT->Add(S"Second", S"World");
    myHT->Add(S"Third", S"!");

    // Displays the properties and values of the Hashtable.
    Console::WriteLine(S"myHT");
    Console::WriteLine(S"  Count:    {0}", __box(myHT->Count));
    Console::WriteLine(S"  Keys and Values:");
    SamplesHashtable::PrintKeysAndValues(myHT);
}
/* 
This code produces the following output.

myHT
Count:    3
Keys and Values:
-KEY-    -VALUE-
Third:    !
Second:    World
First:    Hello
*/ 

[JScript] 
import System
import System.Collections

// Creates and initializes a new Hashtable.
var myHT : Hashtable = 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)
    
function PrintKeysAndValues(myList : Hashtable){
    var myEnumerator : IDictionaryEnumerator = 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 

要求

命名空间: System.Collections

平台: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 系列, .NET Framework 精简版

程序集: Mscorlib (在 Mscorlib.dll 中)

请参见

Hashtable 成员 | System.Collections 命名空间 | IDictionary | IHashCodeProvider | Object.GetHashCode | Object.Equals | DictionaryEntry

posted on 2005-11-06 09:41  henry  阅读(906)  评论(0)    收藏  举报