Hashtable.Add(Object, Object) Método

Definición

Agrega un elemento con la clave y el valor especificados en .Hashtable

public:
 virtual void Add(System::Object ^ key, System::Object ^ value);
public virtual void Add(object key, object value);
abstract member Add : obj * obj -> unit
override this.Add : obj * obj -> unit
Public Overridable Sub Add (key As Object, value As Object)

Parámetros

key
Object

Clave del elemento que se va a agregar.

value
Object

Valor del elemento que se va a agregar. El valor puede ser null.

Implementaciones

Excepciones

key es null.

Ya existe un elemento con la misma clave en .Hashtable

es Hashtable de solo lectura.

O bien

Hashtable tiene un tamaño fijo.

Ejemplos

En el ejemplo siguiente se muestra cómo agregar elementos a .Hashtable

using System;
using System.Collections;
public class SamplesHashtable
{

   public static void Main()
   {
      // Creates and initializes a new Hashtable.
      var myHT = new Hashtable();
      myHT.Add("one", "The");
      myHT.Add("two", "quick");
      myHT.Add("three", "brown");
      myHT.Add("four", "fox");

      // Displays the Hashtable.
      Console.WriteLine("The Hashtable contains the following:");
      PrintKeysAndValues(myHT);
   }

   public static void PrintKeysAndValues( Hashtable myHT )
   {
      Console.WriteLine("\t-KEY-\t-VALUE-");
      foreach (DictionaryEntry de in myHT)
         Console.WriteLine($"\t{de.Key}:\t{de.Value}");
      Console.WriteLine();
   }
}
/*
This code produces the following output.

The Hashtable contains the following:
        -KEY-   -VALUE-
        two:    quick
        three:  brown
        four:   fox
        one:    The
*/
Imports System.Collections

Public Class SamplesHashtable

    Public Shared Sub Main()

        ' Creates and initializes a new Hashtable.
        Dim myHT As New Hashtable()
        myHT.Add("one", "The")
        myHT.Add("two", "quick")
        myHT.Add("three", "brown")
        myHT.Add("four", "fox")

        ' Displays the Hashtable.
        Console.WriteLine("The Hashtable contains the following:")
        PrintKeysAndValues(myHT)

    End Sub

    Public Shared Sub PrintKeysAndValues(myHT As Hashtable)
        Console.WriteLine(vbTab + "-KEY-" + vbTab + "-VALUE-")
        For Each de As DictionaryEntry In myHT
            Console.WriteLine(vbTab + "{0}:" + vbTab + "{1}", de.Key, de.Value)
        Next
        Console.WriteLine()
    End Sub

End Class


' This code produces the following output.
' 
' The Hashtable contains the following:
'         -KEY-   -VALUE-
'         two:    quick
'         one:    The
'         three:  brown
'         four:   fox
'

Comentarios

Una clave no puede ser null, pero un valor puede ser .

Normalmente, un objeto que no tiene ninguna correlación entre su estado y su valor de código hash no se debe usar como clave. Por ejemplo, los objetos String son mejores que los objetos StringBuilder para su uso como claves.

También puede usar la Item[] propiedad para agregar nuevos elementos estableciendo el valor de una clave que no existe en Hashtable; por ejemplo, myCollection["myNonexistentKey"] = myValue. Sin embargo, si la clave especificada ya existe en , Hashtableal establecer la Item[] propiedad se sobrescribe el valor anterior. En cambio, el Add método no modifica los elementos existentes.

Si Count es menor que la capacidad de Hashtable, este método es una O(1) operación. Si es necesario aumentar la capacidad para acomodar el nuevo elemento, este método se convierte en una O(n) operación, donde n es Count.

Se aplica a

Consulte también