Assembly : mscorlib (dans mscorlib.dll)
Syntaxe<SerializableAttribute> _ <ComVisibleAttribute(True)> _ Public Class Hashtable Implements IDictionary, ICollection, IEnumerable, ISerializable, _ IDeserializationCallback, ICloneable
Dim instance As Hashtable
[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
NotesChaque élément est une paire clé/valeur stockée dans un objet DictionaryEntry. Une clé ne peut pas être référence Null (Nothing en Visual Basic), contrairement à une valeur.
Les objets utilisés comme clés par Hashtable sont requis pour substituer la méthode Object.GetHashCode (ou l'interface IHashCodeProvider) et la méthode Object.Equals (ou l'interface IComparer). L'implémentation des deux méthodes et interfaces doit gérer le respect de la casse de la même manière ; sinon, le comportement de Hashtable risque d'être incorrect. Par exemple, lors de la création de Hashtable, vous devez utiliser la classe CaseInsensitiveHashCodeProvider (ou toute implémentation de IHashCodeProvider ignorant la casse) avec la classe CaseInsensitiveComparer (ou toute implémentation de IComparer ne respectant pas la casse).
De plus, ces méthodes doivent donner les mêmes résultats lorsqu'elles sont appelées avec les mêmes paramètres si la clé existe dans Hashtable. Une alternative consiste à utiliser un constructeur Hashtable avec un paramètre IEqualityComparer. Si l'égalité des clés est simplement une égalité des références, l'implémentation héritée de Object.GetHashCode et Object.Equals suffit.
Les objets de clé doivent être immuables tant qu'ils sont utilisés comme clés dans Hashtable.
Quand un élément est ajouté à Hashtable, il est placé dans un compartiment basé sur le code de hachage de la clé. Les recherches suivantes de la clé utiliseront le code de hachage de cette clé pour ne rechercher que dans un compartiment précis, ce qui réduira substantiellement le nombre de comparaisons de clés nécessaire pour trouver un élément.
Le facteur de charge de Hashtable détermine le ratio maximal d'éléments par compartiment. Des facteurs de charge plus petits écourtent les temps moyens de recherche, mais augmentent la consommation de mémoire. Le facteur de charge par défaut est de 1, ce qui représente généralement le meilleur compromis entre la vitesse et la taille. Un facteur de charge différent peut être spécifié si Hashtable est créé.
Lorsque des éléments sont ajoutés à Hashtable, le facteur de charge réel de Hashtable augmente. Lorsque le facteur de charge réel devient égal au facteur de charge spécifié, le nombre de compartiments dans Hashtable est automatiquement augmenté au plus petit nombre premier supérieur à deux fois le nombre actuel de compartiments de Hashtable.
Chaque objet de clé dans Hashtable doit apporter sa propre fonction de hachage, qui est accessible en appelant GetHash. Cependant, tout objet implémentant IHashCodeProvider peut être passé à un constructeur de Hashtable et cette fonction de hachage est utilisée pour tous les objets de la table.
La capacité de Hashtable correspond au nombre d'éléments que peut contenir Hashtable. La capacité initiale par défaut de Hashtable est égale à zéro. Lorsque des éléments sont ajoutés à Hashtable, la capacité augmente automatiquement par réallocation.
L'instruction foreach du langage C# (for each en Visual Basic) requiert le type de chaque élément de la collection. Étant donné que chaque élément de Hashtable est une paire clé/valeur, le type d'élément n'est pas le type de la clé, ni le type de la valeur. Le type d'élément est plutôt DictionaryEntry. Par exemple :
foreach (DictionaryEntry de in myHashtable) {...}
For Each de as DictionaryEntry In myHashtable ... Next de
L'instruction foreach est un wrapper autour de l'énumérateur, qui permet la lecture à partir de la collection, mais non l'écriture dans celle-ci.
Étant donné que la sérialisation et la désérialisation d'un énumérateur pour Hashtable peuvent provoquer la réorganisation des éléments, il n'est pas possible de continuer l'énumération sans appeler la méthode Reset.
ExempleL'exemple suivant illustre la création et l'initialisation de Hashtable, l'exécution de diverses fonctions sur celui-ci, ainsi que l'impression de ses clés et valeurs.
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. */
Hiérarchie d'héritageSystem.Collections.Hashtable
System.Configuration.SettingsAttributeDictionary
System.Configuration.SettingsContext
System.Data.PropertyCollection
Sécurité des threadsHashtable est thread-safe pour une utilisation par plusieurs threads de lecture ou par un seul thread d'écriture. Il n'est pas thread-safe pour une utilisation multithread, lorsque l'un des threads effectue des opérations d'écriture (de mise à jour). Pour prendre en charge plusieurs writers, toutes les opérations sur Hashtable doivent être effectuées via le wrapper retourné par la méthode Synchronized, pourvu qu'aucun thread ne lise l'objet Hashtable.
L'énumération d'une collection n'est intrinsèquement pas une procédure thread-safe. Même lorsqu'une collection est synchronisée, les autres threads peuvent toujours modifier la collection, ce qui entraîne la levée d'une exception par l'énumérateur. Pour garantir la sécurité des threads au cours de l'énumération, vous pouvez soit verrouiller la collection pendant l'ensemble de l'énumération, soit intercepter les exceptions résultant des modifications apportées par les autres threads.
Plates-formesWindows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition
Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.
Informations de version
Outils (masquer)
S'enregistrer
Liste des Membres
Qui est en ligne?
FAQ