Hashtable クラスとは? わかりやすく解説

Hashtable クラス

キーハッシュ コード基づいて編成された、キー/値ペアコレクション表します

名前空間: System.Collections
アセンブリ: 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
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
public class Hashtable implements IDictionary,
 ICollection, 
    IEnumerable, ISerializable, IDeserializationCallback, ICloneable
SerializableAttribute 
ComVisibleAttribute(true) 
public class Hashtable implements 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.Object
  System.Collections.Hashtable
     System.Configuration.SettingsAttributeDictionary
     System.Configuration.SettingsContext
     System.Data.PropertyCollection
スレッド セーフスレッド セーフ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
Hashtable メンバ
System.Collections 名前空間
IDictionary
IHashCodeProvider
Object.GetHashCode
Object.Equals
DictionaryEntry 構造体
System.Collections.Generic.Dictionary
IEqualityComparer



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Hashtable クラス」の関連用語

Hashtable クラスのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Hashtable クラスのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS