Hashtable クラス
アセンブリ: mscorlib (mscorlib.dll 内)

<SerializableAttribute> _ <ComVisibleAttribute(True)> _ Public Class Hashtable Implements IDictionary, ICollection, IEnumerable, ISerializable, _ IDeserializationCallback, ICloneable
[SerializableAttribute] [ComVisibleAttribute(true)] public class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable
[SerializableAttribute] [ComVisibleAttribute(true)] public ref class Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable

各要素は、DictionaryEntry オブジェクトに格納されているキー/値ペアです。キーには null 参照 (Visual Basic では Nothing) は使用できませんが、値は null でもかまいません。
Hashtable でキーとして使用されるオブジェクトは、Object.GetHashCode メソッド (または IHashCodeProvider インターフェイス) および Object.Equals メソッド (または IComparer インターフェイス) をオーバーライドする必要があります。メソッドおよびインターフェイスのどちらの実装でも、大文字と小文字の区別を同じ方法で処理する必要があります。そのように実装されていないと、Hashtable が正しく動作しない場合があります。たとえば、Hashtable を作成するとき、CaseInsensitiveHashCodeProvider クラス (または大文字と小文字を区別しない任意の IHashCodeProvider 実装) は、CaseInsensitiveComparer クラス (または大文字と小文字を区別しない任意の IComparer 実装) と共に使用する必要があります。
また、これらのメソッドは、キーが Hashtable に存在している間に同じパラメータを指定して呼び出された場合は、同じ結果を生成する必要があります。代わりに、Hashtable コンストラクタで IEqualityComparer パラメータを使用することもできます。キーが等値で単純に参照が等値である場合は、Object.GetHashCode および Object.Equals を継承して実装するだけで十分です。
キー オブジェクトは、Hashtable でキーとして使用されている間は不変であることが必要です。
Hashtable に要素が追加されると、その要素はキーのハッシュ コードに基づいてバケットに配置されます。それ以後にキーを検索する際には、そのキーのハッシュ コードを使用して、1 つのバケットだけを検索します。これにより、要素を見つけるために必要となるキーの比較回数を減らすことができます。
Hashtable のテーブル占有率は、バケット数に対する要素数の最大比率を決定します。テーブル占有率を小さくすると、検索時間は平均的に短くなりますが、メモリの消費量は増加します。既定のテーブル占有率は 1.0 です。通常、この値は、検索速度とサイズの最適なバランスを実現します。Hashtable を作成するときに、既定値とは異なるテーブル占有率を指定することもできます。
Hashtable に要素が追加されると、Hashtable の実際のテーブル占有率は大きくなります。実際のテーブル占有率が指定した占有率に達すると、Hashtable のバケット数は、現在の Hashtable のバケット数の 2 倍より大きい範囲で最小の素数になるように、自動的に増やされます。
Hashtable の各キー オブジェクトは、GetHash を呼び出すことによってアクセスできる独自のハッシュ関数を用意する必要があります。ただし、IHashCodeProvider を実装するオブジェクトは Hashtable コンストラクタに渡すことができ、そのハッシュ関数はテーブル内のすべてのオブジェクトに対して使用できます。
Hashtable の容量は、Hashtable が保持できる要素数になります。Hashtable の既定の初期量はゼロです。Hashtable に要素を追加すると、必要に応じて、再割り当てを行うことによって容量が自動的に増加します。
C# 言語の foreach ステートメント (Visual Basic では for each) は、コレクション内の各要素の型を必要とします。Hashtable の各要素はキー/値ペアであるため、要素の型は、キーの型や値の型にはなりません。その代わり、要素の型は DictionaryEntry になります。例 :
foreach (DictionaryEntry de in myHashtable) {...}
For Each de as DictionaryEntry In myHashtable ... Next de
foreach ステートメントは、列挙子のラッパーです。これは、コレクションからの読み取りだけを許可し、コレクションへの書き込みを防ぎます。
Hashtable の列挙子をシリアル化または逆シリアル化すると要素の順番が変更される場合があるため、列挙を続けるためには Reset メソッドを呼び出す必要があります。

Hashtable を作成および初期化し、それに対して各種の関数を実行する方法と、そのキーと値を出力する方法の例を次に示します。
Imports System Imports System.Collections Module Example Sub Main() ' Create a new hash table. ' Dim openWith As New Hashtable() ' Add some elements to the hash table. There are no ' duplicate keys, but some of the values are duplicates. openWith.Add("txt", "notepad.exe") openWith.Add("bmp", "paint.exe") openWith.Add("dib", "paint.exe") openWith.Add("rtf", "wordpad.exe") ' The Add method throws an exception if the new key is ' already in the hash table. Try openWith.Add("txt", "winword.exe") Catch Console.WriteLine("An element with Key = ""txt"" already exists.") End Try ' The Item property is the default property, so you ' can omit its name when accessing elements. Console.WriteLine("For key = ""rtf"", value = {0}.", _ openWith("rtf")) ' The default Item property can be used to change the value ' associated with a key. openWith("rtf") = "winword.exe" Console.WriteLine("For key = ""rtf"", value = {0}.", _ openWith("rtf")) ' If a key does not exist, setting the default Item property ' for that key adds a new key/value pair. openWith("doc") = "winword.exe" ' The default Item property throws an exception if the requested ' key is not in the hash table. Try Console.WriteLine("For key = ""tif"", value = {0}.", _ openWith("tif")) Catch Console.WriteLine("Key = ""tif"" is not found.") End Try ' ContainsKey can be used to test keys before inserting ' them. If Not openWith.ContainsKey("ht") Then openWith.Add("ht", "hypertrm.exe") Console.WriteLine("Value added for key = ""ht"": {0}", _ openWith("ht")) End If ' When you use foreach to enumerate hash table elements, ' the elements are retrieved as KeyValuePair objects. Console.WriteLine() For Each de As DictionaryEntry In openWith Console.WriteLine("Key = {0}, Value = {1}", _ de.Key, de.Value) Next de ' To get the values alone, use the Values property. Dim valueColl As ICollection = openWith.Values ' The elements of the ValueCollection are strongly typed ' with the type that was specified for hash table values. Console.WriteLine() For Each s As String In valueColl Console.WriteLine("Value = {0}", s) Next s ' To get the keys alone, use the Keys property. Dim keyColl As ICollection = openWith.Keys ' The elements of the KeyCollection are strongly typed ' with the type that was specified for hash table keys. Console.WriteLine() For Each s As String In keyColl Console.WriteLine("Key = {0}", s) Next s ' Use the Remove method to remove a key/value pair. Console.WriteLine(vbLf + "Remove(""doc"")") openWith.Remove("doc") If Not openWith.ContainsKey("doc") Then Console.WriteLine("Key ""doc"" is not found.") End If End Sub End Module ' This code example produces the following output: ' 'An element with Key = "txt" already exists. 'For key = "rtf", value = wordpad.exe. 'For key = "rtf", value = winword.exe. 'For key = "tif", value = . 'Value added for key = "ht": hypertrm.exe ' 'Key = dib, Value = paint.exe 'Key = txt, Value = notepad.exe 'Key = ht, Value = hypertrm.exe 'Key = bmp, Value = paint.exe 'Key = rtf, Value = winword.exe 'Key = doc, Value = winword.exe ' 'Value = paint.exe 'Value = notepad.exe 'Value = hypertrm.exe 'Value = paint.exe 'Value = winword.exe 'Value = winword.exe ' 'Key = dib 'Key = txt 'Key = ht 'Key = bmp 'Key = rtf 'Key = doc ' 'Remove("doc") 'Key "doc" is not found.
using System; using System.Collections; class Example { public static void Main() { // Create a new hash table. // Hashtable openWith = new Hashtable(); // Add some elements to the hash table. There are no // duplicate keys, but some of the values are duplicates. openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); // The Add method throws an exception if the new key is // already in the hash table. try { openWith.Add("txt", "winword.exe"); } catch { Console.WriteLine("An element with Key = \"txt\" already exists."); } // The Item property is the default property, so you // can omit its name when accessing elements. Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]); // The default Item property can be used to change the value // associated with a key. openWith["rtf"] = "winword.exe"; Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]); // If a key does not exist, setting the default Item property // for that key adds a new key/value pair. openWith["doc"] = "winword.exe"; // The default Item property throws an exception if the requested // key is not in the hash table. try { Console.WriteLine("For key = \"tif\", value = {0}.", openWith["tif"]); } catch { Console.WriteLine("Key = \"tif\" is not found."); } // ContainsKey can be used to test keys before inserting // them. if (!openWith.ContainsKey("ht")) { openWith.Add("ht", "hypertrm.exe"); Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]); } // When you use foreach to enumerate hash table elements, // the elements are retrieved as KeyValuePair objects. Console.WriteLine(); foreach( DictionaryEntry de in openWith ) { Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value); } // To get the values alone, use the Values property. ICollection valueColl = openWith.Values; // The elements of the ValueCollection are strongly typed // with the type that was specified for hash table values. Console.WriteLine(); foreach( string s in valueColl ) { Console.WriteLine("Value = {0}", s); } // To get the keys alone, use the Keys property. ICollection keyColl = openWith.Keys; // The elements of the KeyCollection are strongly typed // with the type that was specified for hash table keys. Console.WriteLine(); foreach( string s in keyColl ) { Console.WriteLine("Key = {0}", s); } // Use the Remove method to remove a key/value pair. Console.WriteLine("\nRemove(\"doc\")"); openWith.Remove("doc"); if (!openWith.ContainsKey("doc")) { Console.WriteLine("Key \"doc\" is not found."); } } } /* This code example produces the following output: An element with Key = "txt" already exists. For key = "rtf", value = wordpad.exe. For key = "rtf", value = winword.exe. For key = "tif", value = . Value added for key = "ht": hypertrm.exe Key = dib, Value = paint.exe Key = txt, Value = notepad.exe Key = ht, Value = hypertrm.exe Key = bmp, Value = paint.exe Key = rtf, Value = winword.exe Key = doc, Value = winword.exe Value = paint.exe Value = notepad.exe Value = hypertrm.exe Value = paint.exe Value = winword.exe Value = winword.exe Key = dib Key = txt Key = ht Key = bmp Key = rtf Key = doc Remove("doc") Key "doc" is not found. */

System.Collections.Hashtable
System.Configuration.SettingsAttributeDictionary
System.Configuration.SettingsContext
System.Data.PropertyCollection

Hashtable は、複数の読み取りスレッドまたは 1 つの書き込みスレッドで使用される場合はスレッド セーフです。複数のスレッドで使用される場合、いずれかのスレッドが書き込み (更新) 操作を実行すると、スレッド セーフでなくなります。複数の書き込みスレッドをサポートするには、Hashtable オブジェクトを読み取るスレッドが存在しないことと、Hashtable に対するすべての操作を Synchronized メソッドで返されるラッパーを経由して実行することが必要です。
コレクションの列挙処理は、本質的にはスレッド セーフな処理ではありません。コレクションが同期されている場合でも、他のスレッドがそのコレクションを変更する可能性はあり、そのような状況が発生すると列挙子は例外をスローします。列挙処理を確実にスレッド セーフに行うには、列挙中にコレクションをロックするか、他のスレッドによって行われた変更によってスローされる例外をキャッチします。

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition
開発プラットフォームの中には、.NET Framework によってサポートされていないバージョンがあります。サポートされているバージョンについては、「システム要件」を参照してください。


Hashtable メンバ
System.Collections 名前空間
IDictionary
IHashCodeProvider
Object.GetHashCode
Object.Equals
DictionaryEntry 構造体
System.Collections.Generic.Dictionary
IEqualityComparer
- Hashtable クラスのページへのリンク