Hashtable Constructores

Definición

Inicializa una nueva instancia de la clase Hashtable.Initializes a new instance of the Hashtable class.

Sobrecargas

Hashtable()

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga, el proveedor de código hash y el comparador predeterminados.Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.

Hashtable(Int32, Single, IHashCodeProvider, IComparer)
Obsoleto.

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga, el proveedor de código hash y el comparador especificados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, hash code provider, and comparer.

Hashtable(IDictionary, Single, IHashCodeProvider, IComparer)
Obsoleto.

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga, el proveedor de código hash y el comparador especificados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, hash code provider, and comparer.

Hashtable(Int32, Single, IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga y el objeto IEqualityComparer especificados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, and IEqualityComparer object.

Hashtable(Int32, IHashCodeProvider, IComparer)
Obsoleto.

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el proveedor de código hash y el comparador especificados, y el factor de carga predeterminado.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, hash code provider, comparer, and the default load factor.

Hashtable(IDictionary, Single, IEqualityComparer)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga y el objeto IEqualityComparer especificados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor and IEqualityComparer object.

Hashtable(IDictionary, IHashCodeProvider, IComparer)
Obsoleto.

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, utiliza el factor de carga predeterminado, y el proveedor de código hash y comparador especificados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, and the specified hash code provider and comparer. Esta API está obsoleta.This API is obsolete. Para una alternativa, vea Hashtable(IDictionary, IEqualityComparer).For an alternative, see Hashtable(IDictionary, IEqualityComparer).

Hashtable(Int32, Single)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga especificados, y el proveedor de código hash y el comparador predeterminados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity and load factor, and the default hash code provider and comparer.

Hashtable(SerializationInfo, StreamingContext)

Inicializa una nueva instancia vacía de la clase Hashtable que es serializable, utilizando los objetos SerializationInfo y StreamingContext especificados.Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

Hashtable(IHashCodeProvider, IComparer)
Obsoleto.

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga predeterminados, y el proveedor de código hash y el comparador especificados.Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified hash code provider and comparer.

Hashtable(IDictionary, Single)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, utiliza el factor de carga especificado, y el proveedor de código hash y comparador predeterminados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, and the default hash code provider and comparer.

Hashtable(IDictionary, IEqualityComparer)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en un nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to a new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga predeterminado y el objeto IEqualityComparer especificado.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor and the specified IEqualityComparer object.

Hashtable(Int32)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial especificada, y el factor de carga, el proveedor de código hash y el comparador predeterminados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, and the default load factor, hash code provider, and comparer.

Hashtable(IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga predeterminados, y el objeto IEqualityComparer especificado.Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified IEqualityComparer object.

Hashtable(IDictionary)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga, el proveedor de código hash y comparador predeterminados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, hash code provider, and comparer.

Hashtable(Int32, IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el objeto IEqualityComparer especificados, y el factor de carga predeterminado.Initializes a new, empty instance of the Hashtable class using the specified initial capacity and IEqualityComparer, and the default load factor.

Hashtable()

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga, el proveedor de código hash y el comparador predeterminados.Initializes a new, empty instance of the Hashtable class using the default initial capacity, load factor, hash code provider, and comparer.

public:
 Hashtable();
public Hashtable ();
Public Sub New ()

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myComparer : IEqualityComparer
{
public:
    virtual bool Equals(Object^ x, Object^ y) 
    {
        return x->Equals(y);
    }

    virtual int GetHashCode(Object^ obj)
    {
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

ref class myCultureComparer : IEqualityComparer
{
private:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

    virtual bool Equals(Object^ x, Object^ y) 
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    virtual int GetHashCode(Object^ obj)
    {
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

int main()
{
   
   // Create a hash table using the default hash code provider and the default comparer.
   Hashtable^ myHT1 = gcnew Hashtable((IEqualityComparer^)nullptr);
   myHT1->Add( "FIRST", "Hello" );
   myHT1->Add( "SECOND", "World" );
   myHT1->Add( "THIRD", "!" );
   
   // Create a hash table using the specified IEqualityComparer that uses
   // the default Object.Equals to determine equality.
   Hashtable^ myHT2 = gcnew Hashtable(gcnew myComparer());
   myHT2->Add( "FIRST", "Hello" );
   myHT2->Add( "SECOND", "World" );
   myHT2->Add( "THIRD", "!" );
   
   // Create a hash table using a case-insensitive hash code provider and
   // case-insensitive comparer based on the InvariantCulture.
   Hashtable^ myHT3 = gcnew Hashtable(
            CaseInsensitiveHashCodeProvider::DefaultInvariant,
            CaseInsensitiveComparer::DefaultInvariant);
   myHT3->Add( "FIRST", "Hello" );
   myHT3->Add( "SECOND", "World" );
   myHT3->Add( "THIRD", "!" );
   
   // Create a hash table using an IEqualityComparer that is based on
   // the Turkish culture (tr-TR) where "I" is not the uppercase
   // version of "i".
   CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
   Hashtable^ myHT4 = gcnew Hashtable( gcnew myCultureComparer(myCul) );
   myHT4->Add( "FIRST", "Hello" );
   myHT4->Add( "SECOND", "World" );
   myHT4->Add( "THIRD", "!" );
   
   // Search for a key in each hash table.
   Console::WriteLine( "first is in myHT1: {0}", myHT1->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT2: {0}", myHT2->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT3: {0}", myHT3->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT4: {0}", myHT4->ContainsKey( "first" ) );
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: False
first is in myHT3: True
first is in myHT4: False

*/
using System;
using System.Collections;
using System.Globalization;

class myComparer : IEqualityComparer
{
    public new bool Equals(object x, object y)
    {
        return x.Equals(y);
    }

    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        return myComparer.Compare(x, y) == 0;
    }

    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        var myHT1 = new Hashtable();
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the default Object.Equals to determine equality.
        var myHT2 = new Hashtable(new myComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using a case-insensitive hash code provider and
        // case-insensitive comparer based on the InvariantCulture.
        Hashtable myHT3 = new Hashtable(
            CaseInsensitiveHashCodeProvider.DefaultInvariant,
            CaseInsensitiveComparer.DefaultInvariant);
        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        var myCul = new CultureInfo("tr-TR");
        var myHT4 = new Hashtable(new myCultureComparer(myCul));
        myHT4.Add("FIRST", "Hello");
        myHT4.Add("SECOND", "World");
        myHT4.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT4: {myHT4.ContainsKey("first")}");
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: False
first is in myHT3: True
first is in myHT4: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myComparer
    Implements IEqualityComparer
    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return x.Equals(y)
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode

        Return obj.ToString().ToLower().GetHashCode()
    End Function

End Class

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return myComparer.Compare(x, y) = 0
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable

    Public Shared Sub Main()

        ' Create a hash table using the default comparer.
        Dim myHT1 As New Hashtable()
        myHT1.Add("FIRST", "Hello")
        myHT1.Add("SECOND", "World")
        myHT1.Add("THIRD", "!")

        ' Create a hash table using the specified IEqualityComparer that uses
        ' the default Object.Equals to determine equality.
        Dim myHT2 As New Hashtable(New myComparer())
        myHT2.Add("FIRST", "Hello")
        myHT2.Add("SECOND", "World")
        myHT2.Add("THIRD", "!")

        ' Create a hash table using a case-insensitive hash code provider and
        ' case-insensitive comparer based on the InvariantCulture.
        Dim myHT3 As New Hashtable( _
            CaseInsensitiveHashCodeProvider.DefaultInvariant, _
            CaseInsensitiveComparer.DefaultInvariant)
        myHT3.Add("FIRST", "Hello")
        myHT3.Add("SECOND", "World")
        myHT3.Add("THIRD", "!")

        ' Create a hash table using an IEqualityComparer that is based on
        ' the Turkish culture (tr-TR) where "I" is not the uppercase
        ' version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim myHT4 As New Hashtable(New myCultureComparer(myCul))
        myHT4.Add("FIRST", "Hello")
        myHT4.Add("SECOND", "World")
        myHT4.Add("THIRD", "!")

        ' Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT4: {myHT4.ContainsKey("first")}")

    End Sub

End Class

'This code produces the following output.
'Results vary depending on the system's culture settings.

'first is in myHT1: False
'first is in myHT2: False
'first is in myHT3: True
'first is in myHT4: False

Comentarios

La capacidad de una tabla hash se utiliza para calcular el número óptimo de cubos de tabla hash en función del factor de carga.A hash table's capacity is used to calculate the optimal number of hash table buckets based on the load factor. La capacidad aumenta automáticamente según sea necesario.Capacity is automatically increased as required.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash para las claves del Hashtable objeto.The hash code provider dispenses hash codes for keys in the Hashtable object. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

Este constructor es una O(1) operación.This constructor is an O(1) operation.

Consulte también

Se aplica a

Hashtable(Int32, Single, IHashCodeProvider, IComparer)

Precaución

Please use Hashtable(int, float, IEqualityComparer) instead.

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga, el proveedor de código hash y el comparador especificados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, hash code provider, and comparer.

public:
 Hashtable(int capacity, float loadFactor, System::Collections::IHashCodeProvider ^ hcp, System::Collections::IComparer ^ comparer);
[System.Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")]
public Hashtable (int capacity, float loadFactor, System.Collections.IHashCodeProvider? hcp, System.Collections.IComparer? comparer);
[System.Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")]
public Hashtable (int capacity, float loadFactor, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
public Hashtable (int capacity, float loadFactor, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
[<System.Obsolete("Please use Hashtable(int, float, IEqualityComparer) instead.")>]
new System.Collections.Hashtable : int * single * System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
new System.Collections.Hashtable : int * single * System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
Public Sub New (capacity As Integer, loadFactor As Single, hcp As IHashCodeProvider, comparer As IComparer)

Parámetros

capacity
Int32

Número aproximado de elementos que el objeto Hashtable puede contener inicialmente.The approximate number of elements that the Hashtable object can initially contain.

loadFactor
Single

Número incluido en el intervalo de 0,1 a 1,0 que se multiplica por el valor predeterminado que proporciona el mejor rendimiento.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. El resultado es la relación máxima de elementos por sectores de almacenamiento.The result is the maximum ratio of elements to buckets.

hcp
IHashCodeProvider

Objeto IHashCodeProvider que suministra los códigos hash de todas las claves de Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable.

o bien-or- null para utilizar el proveedor predeterminado de código hash, que es la implementación de GetHashCode() de cada clave.null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer

Objeto IComparer que se va a utilizar para determinar si dos claves son iguales.The IComparer object to use to determine whether two keys are equal.

o bien-or- null para utilizar el comparador predeterminado, que es la implementación de cada clave de Equals(Object).null to use the default comparer, which is each key's implementation of Equals(Object).

Atributos

Excepciones

capacity es menor que cero.capacity is less than zero.

o bien-or- loadFactor es menor que 0,1.loadFactor is less than 0.1.

o bien-or- loadFactor es mayor que 1,0.loadFactor is greater than 1.0.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(3, .8f);
        myHT1->Add("FIRST", "Hello");
        myHT1->Add("SECOND", "World");
        myHT1->Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(3, .8f, gcnew myCultureComparer());
        myHT2->Add("FIRST", "Hello");
        myHT2->Add("SECOND", "World");
        myHT2->Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(3, .8f, gcnew myCultureComparer(myCul));
        myHT3->Add("FIRST", "Hello");
        myHT3->Add("SECOND", "World");
        myHT3->Add("THIRD", "!");

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));

    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(3, .8f);
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(3, .8f, new myCultureComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(3, .8f, new myCultureComparer(myCul));

        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable

    Public Shared Sub Main()

        ' Create a hash table using the default comparer.
        Dim myHT1 As New Hashtable(3, System.Convert.ToSingle(0.8))
        myHT1.Add("FIRST", "Hello")
        myHT1.Add("SECOND", "World")
        myHT1.Add("THIRD", "!")

        ' Create a hash table using the specified IEqualityComparer that uses
        ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Dim myHT2 As New Hashtable(3, System.Convert.ToSingle(0.8), _
            New myCultureComparer())

        myHT2.Add("FIRST", "Hello")
        myHT2.Add("SECOND", "World")
        myHT2.Add("THIRD", "!")

        ' Create a hash table using an IEqualityComparer that is based on
        ' the Turkish culture (tr-TR) where "I" is not the uppercase
        ' version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim myHT3 As New Hashtable(3, System.Convert.ToSingle(0.8), _
            New myCultureComparer(myCul))

        myHT3.Add("FIRST", "Hello")
        myHT3.Add("SECOND", "World")
        myHT3.Add("THIRD", "!")

        ' Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

    End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

Al especificar la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al Hashtable objeto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un factor de carga de 1,0 es el mejor equilibrio entre velocidad y tamaño.A load factor of 1.0 is the best balance between speed and size.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

El proveedor de código hash personalizado y el comparador personalizado permiten escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Este constructor es una O(n) operación, donde n es el capacity parámetro.This constructor is an O(n) operation, where n is the capacity parameter.

Consulte también

Se aplica a

Hashtable(IDictionary, Single, IHashCodeProvider, IComparer)

Precaución

Please use Hashtable(IDictionary, float, IEqualityComparer) instead.

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga, el proveedor de código hash y el comparador especificados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, hash code provider, and comparer.

public:
 Hashtable(System::Collections::IDictionary ^ d, float loadFactor, System::Collections::IHashCodeProvider ^ hcp, System::Collections::IComparer ^ comparer);
[System.Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")]
public Hashtable (System.Collections.IDictionary d, float loadFactor, System.Collections.IHashCodeProvider? hcp, System.Collections.IComparer? comparer);
[System.Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")]
public Hashtable (System.Collections.IDictionary d, float loadFactor, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
public Hashtable (System.Collections.IDictionary d, float loadFactor, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
[<System.Obsolete("Please use Hashtable(IDictionary, float, IEqualityComparer) instead.")>]
new System.Collections.Hashtable : System.Collections.IDictionary * single * System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
new System.Collections.Hashtable : System.Collections.IDictionary * single * System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
Public Sub New (d As IDictionary, loadFactor As Single, hcp As IHashCodeProvider, comparer As IComparer)

Parámetros

d
IDictionary

Objeto IDictionary que debe copiarse a un nuevo objeto Hashtable.The IDictionary object to copy to a new Hashtable object.

loadFactor
Single

Número incluido en el intervalo de 0,1 a 1,0 que se multiplica por el valor predeterminado que proporciona el mejor rendimiento.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. El resultado es la relación máxima de elementos por sectores de almacenamiento.The result is the maximum ratio of elements to buckets.

hcp
IHashCodeProvider

Objeto IHashCodeProvider que suministra los códigos hash de todas las claves de Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable.

o bien-or- null para utilizar el proveedor predeterminado de código hash, que es la implementación de GetHashCode() de cada clave.null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer

Objeto IComparer que se va a utilizar para determinar si dos claves son iguales.The IComparer object to use to determine whether two keys are equal.

o bien-or- null para utilizar el comparador predeterminado, que es la implementación de cada clave de Equals(Object).null to use the default comparer, which is each key's implementation of Equals(Object).

Atributos

Excepciones

d es null.d is null.

loadFactor es menor que 0,1.loadFactor is less than 0.1.

o bien-or- loadFactor es mayor que 1,0.loadFactor is greater than 1.0.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
       
       // Create the dictionary.
       SortedList^ mySL = gcnew SortedList;
       mySL->Add( "FIRST", "Hello" );
       mySL->Add( "SECOND", "World" );
       mySL->Add( "THIRD", "!" );
       
       // Create a hash table using the default hash code provider and the default comparer.
       Hashtable^ myHT1 = gcnew Hashtable( mySL, .8f );
       
       // Create a hash table using the specified case-insensitive hash code provider and case-insensitive comparer.
       Hashtable^ myHT2 = gcnew Hashtable( mySL, .8f, gcnew myCultureComparer() );
       
       // Create a hash table using the specified KeyComparer.
       // The KeyComparer uses a case-insensitive hash code provider and a case-insensitive comparer,
       // which are based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
       CultureInfo^ myCul = gcnew CultureInfo( "tr-TR" );
       Hashtable^ myHT3 = gcnew Hashtable( mySL, .8f, gcnew myCultureComparer( myCul ) );
       
       // Search for a key in each hash table.
       Console::WriteLine( "first is in myHT1: {0}", myHT1->ContainsKey( "first" ) );
       Console::WriteLine( "first is in myHT2: {0}", myHT2->ContainsKey( "first" ) );
       Console::WriteLine( "first is in myHT3: {0}", myHT3->ContainsKey( "first" ) );
    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create the dictionary.
        SortedList mySL = new SortedList();
        mySL.Add("FIRST", "Hello");
        mySL.Add("SECOND", "World");
        mySL.Add("THIRD", "!");

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(mySL, .8f);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(mySL, .8f,
            new myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(mySL, .8f, new myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create the dictionary.
      Dim mySL As New SortedList()
      mySL.Add("FIRST", "Hello")
      mySL.Add("SECOND", "World")
      mySL.Add("THIRD", "!")

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(mySL, System.Convert.ToSingle(0.8))

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(mySL, System.Convert.ToSingle(0.8), _
        New myCultureComparer())

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(mySL, System.Convert.ToSingle(0.8), _
        New myCultureComparer(myCul))

      ' Search for a key in each hash table.
      Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
      Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
      Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

La capacidad inicial se establece en el número de elementos del Diccionario de origen.The initial capacity is set to the number of elements in the source dictionary. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un factor de carga de 1,0 es el mejor equilibrio entre velocidad y tamaño.A load factor of 1.0 is the best balance between speed and size.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash para las claves del Hashtable objeto.The hash code provider dispenses hash codes for keys in the Hashtable object. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

El proveedor de código hash personalizado y el comparador personalizado permiten escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Los elementos del nuevo Hashtable se ordenan en el mismo orden en el que el enumerador recorre en iteración el IDictionary objeto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Este constructor es una O(n) operación, donde n es el número de elementos del d parámetro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Se aplica a

Hashtable(Int32, Single, IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el factor de carga y el objeto IEqualityComparer especificados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, and IEqualityComparer object.

public:
 Hashtable(int capacity, float loadFactor, System::Collections::IEqualityComparer ^ equalityComparer);
public Hashtable (int capacity, float loadFactor, System.Collections.IEqualityComparer equalityComparer);
public Hashtable (int capacity, float loadFactor, System.Collections.IEqualityComparer? equalityComparer);
new System.Collections.Hashtable : int * single * System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (capacity As Integer, loadFactor As Single, equalityComparer As IEqualityComparer)

Parámetros

capacity
Int32

Número aproximado de elementos que el objeto Hashtable puede contener inicialmente.The approximate number of elements that the Hashtable object can initially contain.

loadFactor
Single

Número incluido en el intervalo de 0,1 a 1,0 que se multiplica por el valor predeterminado que proporciona el mejor rendimiento.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. El resultado es la relación máxima de elementos por sectores de almacenamiento.The result is the maximum ratio of elements to buckets.

equalityComparer
IEqualityComparer

Objeto IEqualityComparer que define el proveedor de código hash y el comparador que se van a usar con Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.

o bien-or- null para utilizar el proveedor de código hash y el comparador predeterminados.null to use the default hash code provider and the default comparer. El proveedor de código hash predeterminado es la implementación del GetHashCode() de cada clave y el comparador predeterminado es la implementación del Equals(Object) de cada clave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Excepciones

capacity es menor que cero.capacity is less than zero.

o bien-or- loadFactor es menor que 0,1.loadFactor is less than 0.1.

o bien-or- loadFactor es mayor que 1,0.loadFactor is greater than 1.0.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(3, .8f);
        myHT1->Add("FIRST", "Hello");
        myHT1->Add("SECOND", "World");
        myHT1->Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(3, .8f, gcnew myCultureComparer());
        myHT2->Add("FIRST", "Hello");
        myHT2->Add("SECOND", "World");
        myHT2->Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(3, .8f, gcnew myCultureComparer(myCul));
        myHT3->Add("FIRST", "Hello");
        myHT3->Add("SECOND", "World");
        myHT3->Add("THIRD", "!");

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));

    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(3, .8f);
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(3, .8f, new myCultureComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(3, .8f, new myCultureComparer(myCul));

        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable

    Public Shared Sub Main()

        ' Create a hash table using the default comparer.
        Dim myHT1 As New Hashtable(3, System.Convert.ToSingle(0.8))
        myHT1.Add("FIRST", "Hello")
        myHT1.Add("SECOND", "World")
        myHT1.Add("THIRD", "!")

        ' Create a hash table using the specified IEqualityComparer that uses
        ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Dim myHT2 As New Hashtable(3, System.Convert.ToSingle(0.8), _
            New myCultureComparer())

        myHT2.Add("FIRST", "Hello")
        myHT2.Add("SECOND", "World")
        myHT2.Add("THIRD", "!")

        ' Create a hash table using an IEqualityComparer that is based on
        ' the Turkish culture (tr-TR) where "I" is not the uppercase
        ' version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim myHT3 As New Hashtable(3, System.Convert.ToSingle(0.8), _
            New myCultureComparer(myCul))

        myHT3.Add("FIRST", "Hello")
        myHT3.Add("SECOND", "World")
        myHT3.Add("THIRD", "!")

        ' Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

    End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

Al especificar la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al Hashtable objeto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un factor de carga de 1,0 es el mejor equilibrio entre velocidad y tamaño.A load factor of 1.0 is the best balance between speed and size.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El IEqualityComparer objeto incluye el proveedor de código hash y el comparador.The IEqualityComparer object includes both the hash code provider and the comparer. Si IEqualityComparer se utiliza un en el Hashtable constructor, no es necesario que los objetos utilizados como claves en Hashtable no reemplacen Object.GetHashCode los Object.Equals métodos y.If an IEqualityComparer is used in the Hashtable constructor, the objects used as keys in the Hashtable are not required to override the Object.GetHashCode and Object.Equals methods.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

IEqualityComparerPermite escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Este constructor es una O(n) operación, donde n es el capacity parámetro.This constructor is an O(n) operation, where n is the capacity parameter.

Consulte también

Se aplica a

Hashtable(Int32, IHashCodeProvider, IComparer)

Precaución

Please use Hashtable(int, IEqualityComparer) instead.

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial, el proveedor de código hash y el comparador especificados, y el factor de carga predeterminado.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, hash code provider, comparer, and the default load factor.

public:
 Hashtable(int capacity, System::Collections::IHashCodeProvider ^ hcp, System::Collections::IComparer ^ comparer);
[System.Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")]
public Hashtable (int capacity, System.Collections.IHashCodeProvider? hcp, System.Collections.IComparer? comparer);
[System.Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")]
public Hashtable (int capacity, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
public Hashtable (int capacity, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
[<System.Obsolete("Please use Hashtable(int, IEqualityComparer) instead.")>]
new System.Collections.Hashtable : int * System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
new System.Collections.Hashtable : int * System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
Public Sub New (capacity As Integer, hcp As IHashCodeProvider, comparer As IComparer)

Parámetros

capacity
Int32

Número aproximado de elementos que el objeto Hashtable puede contener inicialmente.The approximate number of elements that the Hashtable object can initially contain.

hcp
IHashCodeProvider

Objeto IHashCodeProvider que suministra los códigos hash de todas las claves de Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable.

o bien-or- null para utilizar el proveedor predeterminado de código hash, que es la implementación de GetHashCode() de cada clave.null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer

Objeto IComparer que se va a utilizar para determinar si dos claves son iguales.The IComparer object to use to determine whether two keys are equal.

o bien-or- null para utilizar el comparador predeterminado, que es la implementación de cada clave de Equals(Object).null to use the default comparer, which is each key's implementation of Equals(Object).

Atributos

Excepciones

capacity es menor que cero.capacity is less than zero.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(3);
        myHT1->Add("FIRST", "Hello");
        myHT1->Add("SECOND", "World");
        myHT1->Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(3, gcnew myCultureComparer());
        myHT2->Add("FIRST", "Hello");
        myHT2->Add("SECOND", "World");
        myHT2->Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(3, gcnew myCultureComparer(myCul));
        myHT3->Add("FIRST", "Hello");
        myHT3->Add("SECOND", "World");
        myHT3->Add("THIRD", "!");

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));

    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(3);
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(3, new myCultureComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(3, new myCultureComparer(myCul));
        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(3)
      myHT1.Add("FIRST", "Hello")
      myHT1.Add("SECOND", "World")
      myHT1.Add("THIRD", "!")

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(3, New myCultureComparer())
      myHT2.Add("FIRST", "Hello")
      myHT2.Add("SECOND", "World")
      myHT2.Add("THIRD", "!")

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(3, New myCultureComparer(myCul))
      myHT3.Add("FIRST", "Hello")
      myHT3.Add("SECOND", "World")
      myHT3.Add("THIRD", "!")

      ' Search for a key in each hash table.
      Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
      Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
      Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

Al especificar la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al Hashtable objeto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

El proveedor de código hash personalizado y el comparador personalizado permiten escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Este constructor es una O(n) operación, donde n es el capacity parámetro.This constructor is an O(n) operation, where n is the capacity parameter.

Consulte también

Se aplica a

Hashtable(IDictionary, Single, IEqualityComparer)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga y el objeto IEqualityComparer especificados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor and IEqualityComparer object.

public:
 Hashtable(System::Collections::IDictionary ^ d, float loadFactor, System::Collections::IEqualityComparer ^ equalityComparer);
public Hashtable (System.Collections.IDictionary d, float loadFactor, System.Collections.IEqualityComparer equalityComparer);
public Hashtable (System.Collections.IDictionary d, float loadFactor, System.Collections.IEqualityComparer? equalityComparer);
new System.Collections.Hashtable : System.Collections.IDictionary * single * System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (d As IDictionary, loadFactor As Single, equalityComparer As IEqualityComparer)

Parámetros

d
IDictionary

Objeto IDictionary que debe copiarse a un nuevo objeto Hashtable.The IDictionary object to copy to a new Hashtable object.

loadFactor
Single

Número incluido en el intervalo de 0,1 a 1,0 que se multiplica por el valor predeterminado que proporciona el mejor rendimiento.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. El resultado es la relación máxima de elementos por sectores de almacenamiento.The result is the maximum ratio of elements to buckets.

equalityComparer
IEqualityComparer

Objeto IEqualityComparer que define el proveedor de código hash y el comparador que se van a usar con Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.

o bien-or- null para utilizar el proveedor de código hash y el comparador predeterminados.null to use the default hash code provider and the default comparer. El proveedor de código hash predeterminado es la implementación del GetHashCode() de cada clave y el comparador predeterminado es la implementación del Equals(Object) de cada clave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Excepciones

d es null.d is null.

loadFactor es menor que 0,1.loadFactor is less than 0.1.

o bien-or- loadFactor es mayor que 1,0.loadFactor is greater than 1.0.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
       
       // Create the dictionary.
       SortedList^ mySL = gcnew SortedList;
       mySL->Add( "FIRST", "Hello" );
       mySL->Add( "SECOND", "World" );
       mySL->Add( "THIRD", "!" );
       
       // Create a hash table using the default hash code provider and the default comparer.
       Hashtable^ myHT1 = gcnew Hashtable( mySL, .8f );
       
       // Create a hash table using the specified case-insensitive hash code provider and case-insensitive comparer.
       Hashtable^ myHT2 = gcnew Hashtable( mySL, .8f, gcnew myCultureComparer() );
       
       // Create a hash table using the specified KeyComparer.
       // The KeyComparer uses a case-insensitive hash code provider and a case-insensitive comparer,
       // which are based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
       CultureInfo^ myCul = gcnew CultureInfo( "tr-TR" );
       Hashtable^ myHT3 = gcnew Hashtable( mySL, .8f, gcnew myCultureComparer( myCul ) );
       
       // Search for a key in each hash table.
       Console::WriteLine( "first is in myHT1: {0}", myHT1->ContainsKey( "first" ) );
       Console::WriteLine( "first is in myHT2: {0}", myHT2->ContainsKey( "first" ) );
       Console::WriteLine( "first is in myHT3: {0}", myHT3->ContainsKey( "first" ) );
    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create the dictionary.
        SortedList mySL = new SortedList();
        mySL.Add("FIRST", "Hello");
        mySL.Add("SECOND", "World");
        mySL.Add("THIRD", "!");

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(mySL, .8f);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(mySL, .8f,
            new myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(mySL, .8f, new myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create the dictionary.
      Dim mySL As New SortedList()
      mySL.Add("FIRST", "Hello")
      mySL.Add("SECOND", "World")
      mySL.Add("THIRD", "!")

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(mySL, System.Convert.ToSingle(0.8))

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(mySL, System.Convert.ToSingle(0.8), _
        New myCultureComparer())

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(mySL, System.Convert.ToSingle(0.8), _
        New myCultureComparer(myCul))

      ' Search for a key in each hash table.
      Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
      Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
      Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

La capacidad inicial se establece en el número de elementos del Diccionario de origen.The initial capacity is set to the number of elements in the source dictionary. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un factor de carga de 1,0 es el mejor equilibrio entre velocidad y tamaño.A load factor of 1.0 is the best balance between speed and size.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El IEqualityComparer objeto incluye el proveedor de código hash y el comparador.The IEqualityComparer object includes both the hash code provider and the comparer. Si IEqualityComparer se utiliza en el Hashtable constructor, no es necesario que los objetos utilizados como claves en el Hashtable objeto reemplacen los Object.GetHashCode Object.Equals métodos y.If an IEqualityComparer is used in the Hashtable constructor, the objects used as keys in the Hashtable object are not required to override the Object.GetHashCode and Object.Equals methods.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

IEqualityComparerPermite escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Los elementos del nuevo Hashtable se ordenan en el mismo orden en el que el enumerador recorre en iteración el IDictionary objeto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Este constructor es una O(n) operación, donde n es el número de elementos del d parámetro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Consulte también

Se aplica a

Hashtable(IDictionary, IHashCodeProvider, IComparer)

Precaución

Please use Hashtable(IDictionary, IEqualityComparer) instead.

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, utiliza el factor de carga predeterminado, y el proveedor de código hash y comparador especificados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, and the specified hash code provider and comparer. Esta API está obsoleta.This API is obsolete. Para una alternativa, vea Hashtable(IDictionary, IEqualityComparer).For an alternative, see Hashtable(IDictionary, IEqualityComparer).

public:
 Hashtable(System::Collections::IDictionary ^ d, System::Collections::IHashCodeProvider ^ hcp, System::Collections::IComparer ^ comparer);
[System.Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")]
public Hashtable (System.Collections.IDictionary d, System.Collections.IHashCodeProvider? hcp, System.Collections.IComparer? comparer);
[System.Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")]
public Hashtable (System.Collections.IDictionary d, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
public Hashtable (System.Collections.IDictionary d, System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
[<System.Obsolete("Please use Hashtable(IDictionary, IEqualityComparer) instead.")>]
new System.Collections.Hashtable : System.Collections.IDictionary * System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
new System.Collections.Hashtable : System.Collections.IDictionary * System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
Public Sub New (d As IDictionary, hcp As IHashCodeProvider, comparer As IComparer)

Parámetros

d
IDictionary

Objeto IDictionary que debe copiarse a un nuevo objeto Hashtable.The IDictionary object to copy to a new Hashtable object.

hcp
IHashCodeProvider

Objeto IHashCodeProvider que suministra los códigos hash de todas las claves de Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable.

o bien-or- null para utilizar el proveedor predeterminado de código hash, que es la implementación de GetHashCode() de cada clave.null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer

Objeto IComparer que se va a utilizar para determinar si dos claves son iguales.The IComparer object to use to determine whether two keys are equal.

o bien-or- null para utilizar el comparador predeterminado, que es la implementación de cada clave de Equals(Object).null to use the default comparer, which is each key's implementation of Equals(Object).

Atributos

Excepciones

d es null.d is null.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create the dictionary.
        SortedList^ mySL = gcnew SortedList();
        mySL->Add("FIRST", "Hello");
        mySL->Add("SECOND", "World");
        mySL->Add("THIRD", "!");

        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(mySL);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(mySL, gcnew myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(mySL, gcnew myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));
    }
};

int main()
{
    SamplesHashtable::Main();
};

/* 
This code produces the following output. 
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        return myComparer.Compare(x, y) == 0;
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create the dictionary.
        var mySL = new SortedList();
        mySL.Add("FIRST", "Hello");
        mySL.Add("SECOND", "World");
        mySL.Add("THIRD", "!");

        // Create a hash table using the default comparer.
        var myHT1 = new Hashtable(mySL);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        var myHT2 = new Hashtable(mySL, new myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        var myCul = new CultureInfo("tr-TR");
        var myHT3 = new Hashtable(mySL, new myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}");
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return myComparer.Compare(x, y) = 0
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create the dictionary.
      Dim mySL As New SortedList()
      mySL.Add("FIRST", "Hello")
      mySL.Add("SECOND", "World")
      mySL.Add("THIRD", "!")

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(mySL)

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(mySL, New myCultureComparer())

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(mySL, New myCultureComparer(myCul))

      ' Search for a key in each hash table.
      Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}")
      Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}")
      Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}")

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

La capacidad inicial se establece en el número de elementos del Diccionario de origen.The initial capacity is set to the number of elements in the source dictionary. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash para las claves del Hashtable objeto.The hash code provider dispenses hash codes for keys in the Hashtable object. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

El proveedor de código hash personalizado y el comparador personalizado permiten escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Los elementos del nuevo Hashtable se ordenan en el mismo orden en el que el enumerador recorre en iteración el IDictionary objeto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Este constructor es una O(n) operación, donde n es el número de elementos del d parámetro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Consulte también

Se aplica a

Hashtable(Int32, Single)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga especificados, y el proveedor de código hash y el comparador predeterminados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity and load factor, and the default hash code provider and comparer.

public:
 Hashtable(int capacity, float loadFactor);
public Hashtable (int capacity, float loadFactor);
new System.Collections.Hashtable : int * single -> System.Collections.Hashtable
Public Sub New (capacity As Integer, loadFactor As Single)

Parámetros

capacity
Int32

Número aproximado de elementos que el objeto Hashtable puede contener inicialmente.The approximate number of elements that the Hashtable object can initially contain.

loadFactor
Single

Número incluido en el intervalo de 0,1 a 1,0 que se multiplica por el valor predeterminado que proporciona el mejor rendimiento.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. El resultado es la relación máxima de elementos por sectores de almacenamiento.The result is the maximum ratio of elements to buckets.

Excepciones

capacity es menor que cero.capacity is less than zero.

o bien-or- loadFactor es menor que 0,1.loadFactor is less than 0.1.

o bien-or- loadFactor es mayor que 1,0.loadFactor is greater than 1.0.

capacity está produciendo un desbordamiento.capacity is causing an overflow.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(3, .8f);
        myHT1->Add("FIRST", "Hello");
        myHT1->Add("SECOND", "World");
        myHT1->Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(3, .8f, gcnew myCultureComparer());
        myHT2->Add("FIRST", "Hello");
        myHT2->Add("SECOND", "World");
        myHT2->Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(3, .8f, gcnew myCultureComparer(myCul));
        myHT3->Add("FIRST", "Hello");
        myHT3->Add("SECOND", "World");
        myHT3->Add("THIRD", "!");

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));

    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(3, .8f);
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(3, .8f, new myCultureComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(3, .8f, new myCultureComparer(myCul));

        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable

    Public Shared Sub Main()

        ' Create a hash table using the default comparer.
        Dim myHT1 As New Hashtable(3, System.Convert.ToSingle(0.8))
        myHT1.Add("FIRST", "Hello")
        myHT1.Add("SECOND", "World")
        myHT1.Add("THIRD", "!")

        ' Create a hash table using the specified IEqualityComparer that uses
        ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Dim myHT2 As New Hashtable(3, System.Convert.ToSingle(0.8), _
            New myCultureComparer())

        myHT2.Add("FIRST", "Hello")
        myHT2.Add("SECOND", "World")
        myHT2.Add("THIRD", "!")

        ' Create a hash table using an IEqualityComparer that is based on
        ' the Turkish culture (tr-TR) where "I" is not the uppercase
        ' version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim myHT3 As New Hashtable(3, System.Convert.ToSingle(0.8), _
            New myCultureComparer(myCul))

        myHT3.Add("FIRST", "Hello")
        myHT3.Add("SECOND", "World")
        myHT3.Add("THIRD", "!")

        ' Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

    End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

Al especificar la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al Hashtable objeto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un factor de carga de 1,0 es el mejor equilibrio entre velocidad y tamaño.A load factor of 1.0 is the best balance between speed and size.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

Este constructor es una O(n) operación, donde n es el capacity parámetro.This constructor is an O(n) operation, where n is the capacity parameter.

Consulte también

Se aplica a

Hashtable(SerializationInfo, StreamingContext)

Inicializa una nueva instancia vacía de la clase Hashtable que es serializable, utilizando los objetos SerializationInfo y StreamingContext especificados.Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

protected:
 Hashtable(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Hashtable (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Collections.Hashtable : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Collections.Hashtable
Protected Sub New (info As SerializationInfo, context As StreamingContext)

Parámetros

info
SerializationInfo

Objeto SerializationInfo que contiene la información que se requiere para serializar el objeto Hashtable.A SerializationInfo object containing the information required to serialize the Hashtable object.

context
StreamingContext

Objeto StreamingContext que contiene el origen y el destino de la secuencia serializada asociada al Hashtable.A StreamingContext object containing the source and destination of the serialized stream associated with the Hashtable.

Excepciones

info es null.info is null.

Comentarios

La capacidad de una tabla hash se utiliza para calcular el número óptimo de cubos de tabla hash en función del factor de carga.A hash table's capacity is used to calculate the optimal number of hash table buckets based on the load factor. La capacidad aumenta automáticamente según sea necesario.Capacity is automatically increased as required.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash para las claves del Hashtable objeto.The hash code provider dispenses hash codes for keys in the Hashtable object. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

Este constructor es una O(n) operación, donde n es Count .This constructor is an O(n) operation, where n is Count.

Dado que la serialización y deserialización de un enumerador para un Hashtable puede hacer que los elementos se reordenen, no es posible continuar la enumeración sin llamar al Reset método.Because serializing and deserializing an enumerator for a Hashtable can cause the elements to become reordered, it is not possible to continue enumeration without calling the Reset method.

Consulte también

Se aplica a

Hashtable(IHashCodeProvider, IComparer)

Precaución

Please use Hashtable(IEqualityComparer) instead.

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga predeterminados, y el proveedor de código hash y el comparador especificados.Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified hash code provider and comparer.

public:
 Hashtable(System::Collections::IHashCodeProvider ^ hcp, System::Collections::IComparer ^ comparer);
[System.Obsolete("Please use Hashtable(IEqualityComparer) instead.")]
public Hashtable (System.Collections.IHashCodeProvider? hcp, System.Collections.IComparer? comparer);
[System.Obsolete("Please use Hashtable(IEqualityComparer) instead.")]
public Hashtable (System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
public Hashtable (System.Collections.IHashCodeProvider hcp, System.Collections.IComparer comparer);
[<System.Obsolete("Please use Hashtable(IEqualityComparer) instead.")>]
new System.Collections.Hashtable : System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
new System.Collections.Hashtable : System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
Public Sub New (hcp As IHashCodeProvider, comparer As IComparer)

Parámetros

hcp
IHashCodeProvider

Objeto IHashCodeProvider que suministra los códigos hash de todas las claves del objeto Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable object.

o bien-or- null para utilizar el proveedor predeterminado de código hash, que es la implementación de GetHashCode() de cada clave.null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer

Objeto IComparer que se va a utilizar para determinar si dos claves son iguales.The IComparer object to use to determine whether two keys are equal.

o bien-or- null para utilizar el comparador predeterminado, que es la implementación de cada clave de Equals(Object).null to use the default comparer, which is each key's implementation of Equals(Object).

Atributos

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myComparer : IEqualityComparer
{
public:
    virtual bool Equals(Object^ x, Object^ y) 
    {
        return x->Equals(y);
    }

    virtual int GetHashCode(Object^ obj)
    {
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

ref class myCultureComparer : IEqualityComparer
{
private:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

    virtual bool Equals(Object^ x, Object^ y) 
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    virtual int GetHashCode(Object^ obj)
    {
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

int main()
{
   
   // Create a hash table using the default hash code provider and the default comparer.
   Hashtable^ myHT1 = gcnew Hashtable((IEqualityComparer^)nullptr);
   myHT1->Add( "FIRST", "Hello" );
   myHT1->Add( "SECOND", "World" );
   myHT1->Add( "THIRD", "!" );
   
   // Create a hash table using the specified IEqualityComparer that uses
   // the default Object.Equals to determine equality.
   Hashtable^ myHT2 = gcnew Hashtable(gcnew myComparer());
   myHT2->Add( "FIRST", "Hello" );
   myHT2->Add( "SECOND", "World" );
   myHT2->Add( "THIRD", "!" );
   
   // Create a hash table using a case-insensitive hash code provider and
   // case-insensitive comparer based on the InvariantCulture.
   Hashtable^ myHT3 = gcnew Hashtable(
            CaseInsensitiveHashCodeProvider::DefaultInvariant,
            CaseInsensitiveComparer::DefaultInvariant);
   myHT3->Add( "FIRST", "Hello" );
   myHT3->Add( "SECOND", "World" );
   myHT3->Add( "THIRD", "!" );
   
   // Create a hash table using an IEqualityComparer that is based on
   // the Turkish culture (tr-TR) where "I" is not the uppercase
   // version of "i".
   CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
   Hashtable^ myHT4 = gcnew Hashtable( gcnew myCultureComparer(myCul) );
   myHT4->Add( "FIRST", "Hello" );
   myHT4->Add( "SECOND", "World" );
   myHT4->Add( "THIRD", "!" );
   
   // Search for a key in each hash table.
   Console::WriteLine( "first is in myHT1: {0}", myHT1->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT2: {0}", myHT2->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT3: {0}", myHT3->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT4: {0}", myHT4->ContainsKey( "first" ) );
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: False
first is in myHT3: True
first is in myHT4: False

*/
using System;
using System.Collections;
using System.Globalization;

class myComparer : IEqualityComparer
{
    public new bool Equals(object x, object y)
    {
        return x.Equals(y);
    }

    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        return myComparer.Compare(x, y) == 0;
    }

    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        var myHT1 = new Hashtable();
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the default Object.Equals to determine equality.
        var myHT2 = new Hashtable(new myComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using a case-insensitive hash code provider and
        // case-insensitive comparer based on the InvariantCulture.
        Hashtable myHT3 = new Hashtable(
            CaseInsensitiveHashCodeProvider.DefaultInvariant,
            CaseInsensitiveComparer.DefaultInvariant);
        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        var myCul = new CultureInfo("tr-TR");
        var myHT4 = new Hashtable(new myCultureComparer(myCul));
        myHT4.Add("FIRST", "Hello");
        myHT4.Add("SECOND", "World");
        myHT4.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT4: {myHT4.ContainsKey("first")}");
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: False
first is in myHT3: True
first is in myHT4: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myComparer
    Implements IEqualityComparer
    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return x.Equals(y)
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode

        Return obj.ToString().ToLower().GetHashCode()
    End Function

End Class

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return myComparer.Compare(x, y) = 0
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable

    Public Shared Sub Main()

        ' Create a hash table using the default comparer.
        Dim myHT1 As New Hashtable()
        myHT1.Add("FIRST", "Hello")
        myHT1.Add("SECOND", "World")
        myHT1.Add("THIRD", "!")

        ' Create a hash table using the specified IEqualityComparer that uses
        ' the default Object.Equals to determine equality.
        Dim myHT2 As New Hashtable(New myComparer())
        myHT2.Add("FIRST", "Hello")
        myHT2.Add("SECOND", "World")
        myHT2.Add("THIRD", "!")

        ' Create a hash table using a case-insensitive hash code provider and
        ' case-insensitive comparer based on the InvariantCulture.
        Dim myHT3 As New Hashtable( _
            CaseInsensitiveHashCodeProvider.DefaultInvariant, _
            CaseInsensitiveComparer.DefaultInvariant)
        myHT3.Add("FIRST", "Hello")
        myHT3.Add("SECOND", "World")
        myHT3.Add("THIRD", "!")

        ' Create a hash table using an IEqualityComparer that is based on
        ' the Turkish culture (tr-TR) where "I" is not the uppercase
        ' version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim myHT4 As New Hashtable(New myCultureComparer(myCul))
        myHT4.Add("FIRST", "Hello")
        myHT4.Add("SECOND", "World")
        myHT4.Add("THIRD", "!")

        ' Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT4: {myHT4.ContainsKey("first")}")

    End Sub

End Class

'This code produces the following output.
'Results vary depending on the system's culture settings.

'first is in myHT1: False
'first is in myHT2: False
'first is in myHT3: True
'first is in myHT4: False

Comentarios

La capacidad de una tabla hash se utiliza para calcular el número óptimo de cubos de tabla hash en función del factor de carga.A hash table's capacity is used to calculate the optimal number of hash table buckets based on the load factor. La capacidad aumenta automáticamente según sea necesario.Capacity is automatically increased as required.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash para las claves del Hashtable objeto.The hash code provider dispenses hash codes for keys in the Hashtable object. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

El proveedor de código hash personalizado y el comparador personalizado permiten escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Este constructor es una O(1) operación.This constructor is an O(1) operation.

Consulte también

Se aplica a

Hashtable(IDictionary, Single)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, utiliza el factor de carga especificado, y el proveedor de código hash y comparador predeterminados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the specified load factor, and the default hash code provider and comparer.

public:
 Hashtable(System::Collections::IDictionary ^ d, float loadFactor);
public Hashtable (System.Collections.IDictionary d, float loadFactor);
new System.Collections.Hashtable : System.Collections.IDictionary * single -> System.Collections.Hashtable
Public Sub New (d As IDictionary, loadFactor As Single)

Parámetros

d
IDictionary

Objeto IDictionary que debe copiarse a un nuevo objeto Hashtable.The IDictionary object to copy to a new Hashtable object.

loadFactor
Single

Número incluido en el intervalo de 0,1 a 1,0 que se multiplica por el valor predeterminado que proporciona el mejor rendimiento.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. El resultado es la relación máxima de elementos por sectores de almacenamiento.The result is the maximum ratio of elements to buckets.

Excepciones

d es null.d is null.

loadFactor es menor que 0,1.loadFactor is less than 0.1.

o bien-or- loadFactor es mayor que 1,0.loadFactor is greater than 1.0.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
       
       // Create the dictionary.
       SortedList^ mySL = gcnew SortedList;
       mySL->Add( "FIRST", "Hello" );
       mySL->Add( "SECOND", "World" );
       mySL->Add( "THIRD", "!" );
       
       // Create a hash table using the default hash code provider and the default comparer.
       Hashtable^ myHT1 = gcnew Hashtable( mySL, .8f );
       
       // Create a hash table using the specified case-insensitive hash code provider and case-insensitive comparer.
       Hashtable^ myHT2 = gcnew Hashtable( mySL, .8f, gcnew myCultureComparer() );
       
       // Create a hash table using the specified KeyComparer.
       // The KeyComparer uses a case-insensitive hash code provider and a case-insensitive comparer,
       // which are based on the Turkish culture (tr-TR), where "I" is not the uppercase version of "i".
       CultureInfo^ myCul = gcnew CultureInfo( "tr-TR" );
       Hashtable^ myHT3 = gcnew Hashtable( mySL, .8f, gcnew myCultureComparer( myCul ) );
       
       // Search for a key in each hash table.
       Console::WriteLine( "first is in myHT1: {0}", myHT1->ContainsKey( "first" ) );
       Console::WriteLine( "first is in myHT2: {0}", myHT2->ContainsKey( "first" ) );
       Console::WriteLine( "first is in myHT3: {0}", myHT3->ContainsKey( "first" ) );
    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create the dictionary.
        SortedList mySL = new SortedList();
        mySL.Add("FIRST", "Hello");
        mySL.Add("SECOND", "World");
        mySL.Add("THIRD", "!");

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(mySL, .8f);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(mySL, .8f,
            new myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(mySL, .8f, new myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create the dictionary.
      Dim mySL As New SortedList()
      mySL.Add("FIRST", "Hello")
      mySL.Add("SECOND", "World")
      mySL.Add("THIRD", "!")

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(mySL, System.Convert.ToSingle(0.8))

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(mySL, System.Convert.ToSingle(0.8), _
        New myCultureComparer())

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(mySL, System.Convert.ToSingle(0.8), _
        New myCultureComparer(myCul))

      ' Search for a key in each hash table.
      Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
      Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
      Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

La capacidad inicial se establece en el número de elementos del Diccionario de origen.The initial capacity is set to the number of elements in the source dictionary. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un factor de carga de 1,0 es el mejor equilibrio entre velocidad y tamaño.A load factor of 1.0 is the best balance between speed and size.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash para las claves del Hashtable objeto.The hash code provider dispenses hash codes for keys in the Hashtable object. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

Los elementos del nuevo Hashtable se ordenan en el mismo orden en el que el enumerador recorre en iteración el IDictionary objeto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Este constructor es una O(n) operación, donde n es el número de elementos del d parámetro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Consulte también

Se aplica a

Hashtable(IDictionary, IEqualityComparer)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en un nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to a new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga predeterminado y el objeto IEqualityComparer especificado.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor and the specified IEqualityComparer object.

public:
 Hashtable(System::Collections::IDictionary ^ d, System::Collections::IEqualityComparer ^ equalityComparer);
public Hashtable (System.Collections.IDictionary d, System.Collections.IEqualityComparer equalityComparer);
public Hashtable (System.Collections.IDictionary d, System.Collections.IEqualityComparer? equalityComparer);
new System.Collections.Hashtable : System.Collections.IDictionary * System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (d As IDictionary, equalityComparer As IEqualityComparer)

Parámetros

d
IDictionary

Objeto IDictionary que debe copiarse a un nuevo objeto Hashtable.The IDictionary object to copy to a new Hashtable object.

equalityComparer
IEqualityComparer

Objeto IEqualityComparer que define el proveedor de código hash y el comparador que se van a usar con Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.

o bien-or- null para utilizar el proveedor de código hash y el comparador predeterminados.null to use the default hash code provider and the default comparer. El proveedor de código hash predeterminado es la implementación del GetHashCode() de cada clave y el comparador predeterminado es la implementación del Equals(Object) de cada clave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Excepciones

d es null.d is null.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create the dictionary.
        SortedList^ mySL = gcnew SortedList();
        mySL->Add("FIRST", "Hello");
        mySL->Add("SECOND", "World");
        mySL->Add("THIRD", "!");

        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(mySL);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(mySL, gcnew myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(mySL, gcnew myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));
    }
};

int main()
{
    SamplesHashtable::Main();
};

/* 
This code produces the following output. 
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        return myComparer.Compare(x, y) == 0;
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create the dictionary.
        var mySL = new SortedList();
        mySL.Add("FIRST", "Hello");
        mySL.Add("SECOND", "World");
        mySL.Add("THIRD", "!");

        // Create a hash table using the default comparer.
        var myHT1 = new Hashtable(mySL);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        var myHT2 = new Hashtable(mySL, new myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        var myCul = new CultureInfo("tr-TR");
        var myHT3 = new Hashtable(mySL, new myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}");
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return myComparer.Compare(x, y) = 0
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create the dictionary.
      Dim mySL As New SortedList()
      mySL.Add("FIRST", "Hello")
      mySL.Add("SECOND", "World")
      mySL.Add("THIRD", "!")

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(mySL)

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(mySL, New myCultureComparer())

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(mySL, New myCultureComparer(myCul))

      ' Search for a key in each hash table.
      Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}")
      Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}")
      Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}")

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

La capacidad inicial se establece en el número de elementos del Diccionario de origen.The initial capacity is set to the number of elements in the source dictionary. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El IEqualityComparer objeto incluye el proveedor de código hash y el comparador.The IEqualityComparer object includes both the hash code provider and the comparer. Si IEqualityComparer se utiliza en el Hashtable constructor, no es necesario que los objetos utilizados como claves en el Hashtable objeto reemplacen los Object.GetHashCode Object.Equals métodos y.If an IEqualityComparer is used in the Hashtable constructor, the objects used as keys in the Hashtable object are not required to override the Object.GetHashCode and Object.Equals methods.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

IEqualityComparerPermite escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Los elementos del nuevo Hashtable se ordenan en el mismo orden en el que el enumerador recorre en iteración el IDictionary objeto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Este constructor es una O(n) operación, donde n es el número de elementos del d parámetro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Consulte también

Se aplica a

Hashtable(Int32)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial especificada, y el factor de carga, el proveedor de código hash y el comparador predeterminados.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, and the default load factor, hash code provider, and comparer.

public:
 Hashtable(int capacity);
public Hashtable (int capacity);
new System.Collections.Hashtable : int -> System.Collections.Hashtable
Public Sub New (capacity As Integer)

Parámetros

capacity
Int32

Número aproximado de elementos que el objeto Hashtable puede contener inicialmente.The approximate number of elements that the Hashtable object can initially contain.

Excepciones

capacity es menor que cero.capacity is less than zero.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(3);
        myHT1->Add("FIRST", "Hello");
        myHT1->Add("SECOND", "World");
        myHT1->Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(3, gcnew myCultureComparer());
        myHT2->Add("FIRST", "Hello");
        myHT2->Add("SECOND", "World");
        myHT2->Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(3, gcnew myCultureComparer(myCul));
        myHT3->Add("FIRST", "Hello");
        myHT3->Add("SECOND", "World");
        myHT3->Add("THIRD", "!");

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));

    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(3);
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(3, new myCultureComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(3, new myCultureComparer(myCul));
        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(3)
      myHT1.Add("FIRST", "Hello")
      myHT1.Add("SECOND", "World")
      myHT1.Add("THIRD", "!")

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(3, New myCultureComparer())
      myHT2.Add("FIRST", "Hello")
      myHT2.Add("SECOND", "World")
      myHT2.Add("THIRD", "!")

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(3, New myCultureComparer(myCul))
      myHT3.Add("FIRST", "Hello")
      myHT3.Add("SECOND", "World")
      myHT3.Add("THIRD", "!")

      ' Search for a key in each hash table.
      Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
      Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
      Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

Al especificar la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al Hashtable objeto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

Este constructor es una O(n) operación, donde n es capacity .This constructor is an O(n) operation, where n is capacity.

Consulte también

Se aplica a

Hashtable(IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el factor de carga predeterminados, y el objeto IEqualityComparer especificado.Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified IEqualityComparer object.

public:
 Hashtable(System::Collections::IEqualityComparer ^ equalityComparer);
public Hashtable (System.Collections.IEqualityComparer equalityComparer);
public Hashtable (System.Collections.IEqualityComparer? equalityComparer);
new System.Collections.Hashtable : System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (equalityComparer As IEqualityComparer)

Parámetros

equalityComparer
IEqualityComparer

Objeto IEqualityComparer que define el proveedor de código hash y el comparador que se van a utilizar con el objeto Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable object.

o bien-or- null para utilizar el proveedor de código hash y el comparador predeterminados.null to use the default hash code provider and the default comparer. El proveedor de código hash predeterminado es la implementación del GetHashCode() de cada clave y el comparador predeterminado es la implementación del Equals(Object) de cada clave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myComparer : IEqualityComparer
{
public:
    virtual bool Equals(Object^ x, Object^ y) 
    {
        return x->Equals(y);
    }

    virtual int GetHashCode(Object^ obj)
    {
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

ref class myCultureComparer : IEqualityComparer
{
private:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

    virtual bool Equals(Object^ x, Object^ y) 
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    virtual int GetHashCode(Object^ obj)
    {
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

int main()
{
   
   // Create a hash table using the default hash code provider and the default comparer.
   Hashtable^ myHT1 = gcnew Hashtable((IEqualityComparer^)nullptr);
   myHT1->Add( "FIRST", "Hello" );
   myHT1->Add( "SECOND", "World" );
   myHT1->Add( "THIRD", "!" );
   
   // Create a hash table using the specified IEqualityComparer that uses
   // the default Object.Equals to determine equality.
   Hashtable^ myHT2 = gcnew Hashtable(gcnew myComparer());
   myHT2->Add( "FIRST", "Hello" );
   myHT2->Add( "SECOND", "World" );
   myHT2->Add( "THIRD", "!" );
   
   // Create a hash table using a case-insensitive hash code provider and
   // case-insensitive comparer based on the InvariantCulture.
   Hashtable^ myHT3 = gcnew Hashtable(
            CaseInsensitiveHashCodeProvider::DefaultInvariant,
            CaseInsensitiveComparer::DefaultInvariant);
   myHT3->Add( "FIRST", "Hello" );
   myHT3->Add( "SECOND", "World" );
   myHT3->Add( "THIRD", "!" );
   
   // Create a hash table using an IEqualityComparer that is based on
   // the Turkish culture (tr-TR) where "I" is not the uppercase
   // version of "i".
   CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
   Hashtable^ myHT4 = gcnew Hashtable( gcnew myCultureComparer(myCul) );
   myHT4->Add( "FIRST", "Hello" );
   myHT4->Add( "SECOND", "World" );
   myHT4->Add( "THIRD", "!" );
   
   // Search for a key in each hash table.
   Console::WriteLine( "first is in myHT1: {0}", myHT1->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT2: {0}", myHT2->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT3: {0}", myHT3->ContainsKey( "first" ) );
   Console::WriteLine( "first is in myHT4: {0}", myHT4->ContainsKey( "first" ) );
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: False
first is in myHT3: True
first is in myHT4: False

*/
using System;
using System.Collections;
using System.Globalization;

class myComparer : IEqualityComparer
{
    public new bool Equals(object x, object y)
    {
        return x.Equals(y);
    }

    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        return myComparer.Compare(x, y) == 0;
    }

    public int GetHashCode(object obj)
    {
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        var myHT1 = new Hashtable();
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the default Object.Equals to determine equality.
        var myHT2 = new Hashtable(new myComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using a case-insensitive hash code provider and
        // case-insensitive comparer based on the InvariantCulture.
        Hashtable myHT3 = new Hashtable(
            CaseInsensitiveHashCodeProvider.DefaultInvariant,
            CaseInsensitiveComparer.DefaultInvariant);
        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        var myCul = new CultureInfo("tr-TR");
        var myHT4 = new Hashtable(new myCultureComparer(myCul));
        myHT4.Add("FIRST", "Hello");
        myHT4.Add("SECOND", "World");
        myHT4.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT4: {myHT4.ContainsKey("first")}");
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: False
first is in myHT3: True
first is in myHT4: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myComparer
    Implements IEqualityComparer
    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return x.Equals(y)
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode

        Return obj.ToString().ToLower().GetHashCode()
    End Function

End Class

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return myComparer.Compare(x, y) = 0
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable

    Public Shared Sub Main()

        ' Create a hash table using the default comparer.
        Dim myHT1 As New Hashtable()
        myHT1.Add("FIRST", "Hello")
        myHT1.Add("SECOND", "World")
        myHT1.Add("THIRD", "!")

        ' Create a hash table using the specified IEqualityComparer that uses
        ' the default Object.Equals to determine equality.
        Dim myHT2 As New Hashtable(New myComparer())
        myHT2.Add("FIRST", "Hello")
        myHT2.Add("SECOND", "World")
        myHT2.Add("THIRD", "!")

        ' Create a hash table using a case-insensitive hash code provider and
        ' case-insensitive comparer based on the InvariantCulture.
        Dim myHT3 As New Hashtable( _
            CaseInsensitiveHashCodeProvider.DefaultInvariant, _
            CaseInsensitiveComparer.DefaultInvariant)
        myHT3.Add("FIRST", "Hello")
        myHT3.Add("SECOND", "World")
        myHT3.Add("THIRD", "!")

        ' Create a hash table using an IEqualityComparer that is based on
        ' the Turkish culture (tr-TR) where "I" is not the uppercase
        ' version of "i".
        Dim myCul As New CultureInfo("tr-TR")
        Dim myHT4 As New Hashtable(New myCultureComparer(myCul))
        myHT4.Add("FIRST", "Hello")
        myHT4.Add("SECOND", "World")
        myHT4.Add("THIRD", "!")

        ' Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}")
        Console.WriteLine($"first is in myHT4: {myHT4.ContainsKey("first")}")

    End Sub

End Class

'This code produces the following output.
'Results vary depending on the system's culture settings.

'first is in myHT1: False
'first is in myHT2: False
'first is in myHT3: True
'first is in myHT4: False

Comentarios

La capacidad de una tabla hash se utiliza para calcular el número óptimo de cubos de tabla hash en función del factor de carga.A hash table's capacity is used to calculate the optimal number of hash table buckets based on the load factor. La capacidad aumenta automáticamente según sea necesario.Capacity is automatically increased as required.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El IEqualityComparer objeto incluye el proveedor de código hash y el comparador.The IEqualityComparer object includes both the hash code provider and the comparer. Si IEqualityComparer se utiliza en el Hashtable constructor, no es necesario que los objetos utilizados como claves en el Hashtable objeto reemplacen los Object.GetHashCode Object.Equals métodos y.If an IEqualityComparer is used in the Hashtable constructor, the objects used as keys in the Hashtable object are not required to override the Object.GetHashCode and Object.Equals methods.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

IEqualityComparerPermite escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Este constructor es una O(1) operación.This constructor is an O(1) operation.

Consulte también

Se aplica a

Hashtable(IDictionary)

Inicializa una nueva instancia de la clase Hashtable copiando los elementos del diccionario especificado en el nuevo objeto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. El nuevo objeto Hashtable tiene una capacidad inicial igual al número de elementos copiados, y utiliza el factor de carga, el proveedor de código hash y comparador predeterminados.The new Hashtable object has an initial capacity equal to the number of elements copied, and uses the default load factor, hash code provider, and comparer.

public:
 Hashtable(System::Collections::IDictionary ^ d);
public Hashtable (System.Collections.IDictionary d);
new System.Collections.Hashtable : System.Collections.IDictionary -> System.Collections.Hashtable
Public Sub New (d As IDictionary)

Parámetros

d
IDictionary

Objeto IDictionary que debe copiarse a un nuevo objeto Hashtable.The IDictionary object to copy to a new Hashtable object.

Excepciones

d es null.d is null.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create the dictionary.
        SortedList^ mySL = gcnew SortedList();
        mySL->Add("FIRST", "Hello");
        mySL->Add("SECOND", "World");
        mySL->Add("THIRD", "!");

        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(mySL);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(mySL, gcnew myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(mySL, gcnew myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));
    }
};

int main()
{
    SamplesHashtable::Main();
};

/* 
This code produces the following output. 
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        return myComparer.Compare(x, y) == 0;
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create the dictionary.
        var mySL = new SortedList();
        mySL.Add("FIRST", "Hello");
        mySL.Add("SECOND", "World");
        mySL.Add("THIRD", "!");

        // Create a hash table using the default comparer.
        var myHT1 = new Hashtable(mySL);

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        var myHT2 = new Hashtable(mySL, new myCultureComparer());

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        var myCul = new CultureInfo("tr-TR");
        var myHT3 = new Hashtable(mySL, new myCultureComparer(myCul));

        // Search for a key in each hash table.
        Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}");
        Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}");
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        Return myComparer.Compare(x, y) = 0
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create the dictionary.
      Dim mySL As New SortedList()
      mySL.Add("FIRST", "Hello")
      mySL.Add("SECOND", "World")
      mySL.Add("THIRD", "!")

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(mySL)

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(mySL, New myCultureComparer())

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(mySL, New myCultureComparer(myCul))

      ' Search for a key in each hash table.
      Console.WriteLine($"first is in myHT1: {myHT1.ContainsKey("first")}")
      Console.WriteLine($"first is in myHT2: {myHT2.ContainsKey("first")}")
      Console.WriteLine($"first is in myHT3: {myHT3.ContainsKey("first")}")

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

La capacidad inicial se establece en el número de elementos del Diccionario de origen.The initial capacity is set to the number of elements in the source dictionary. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El proveedor de código hash dispensará los códigos hash para las claves del Hashtable objeto.The hash code provider dispenses hash codes for keys in the Hashtable object. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

Los elementos del nuevo Hashtable se ordenan en el mismo orden en el que el enumerador recorre en iteración el IDictionary objeto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Este constructor es una O(n) operación, donde n es el número de elementos del d parámetro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Consulte también

Se aplica a

Hashtable(Int32, IEqualityComparer)

Inicializa una nueva instancia vacía de la clase Hashtable utilizando la capacidad inicial y el objeto IEqualityComparer especificados, y el factor de carga predeterminado.Initializes a new, empty instance of the Hashtable class using the specified initial capacity and IEqualityComparer, and the default load factor.

public:
 Hashtable(int capacity, System::Collections::IEqualityComparer ^ equalityComparer);
public Hashtable (int capacity, System.Collections.IEqualityComparer equalityComparer);
public Hashtable (int capacity, System.Collections.IEqualityComparer? equalityComparer);
new System.Collections.Hashtable : int * System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (capacity As Integer, equalityComparer As IEqualityComparer)

Parámetros

capacity
Int32

Número aproximado de elementos que el objeto Hashtable puede contener inicialmente.The approximate number of elements that the Hashtable object can initially contain.

equalityComparer
IEqualityComparer

Objeto IEqualityComparer que define el proveedor de código hash y el comparador que se van a usar con Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.

o bien-or- null para utilizar el proveedor de código hash y el comparador predeterminados.null to use the default hash code provider and the default comparer. El proveedor de código hash predeterminado es la implementación del GetHashCode() de cada clave y el comparador predeterminado es la implementación del Equals(Object) de cada clave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Excepciones

capacity es menor que cero.capacity is less than zero.

Ejemplos

En el ejemplo de código siguiente se crean tablas hash con distintos Hashtable constructores y se muestran las diferencias en el comportamiento de las tablas hash, incluso si cada una de ellas contiene los mismos elementos.The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables, even if each one contains the same elements.

using namespace System;
using namespace System::Collections;
using namespace System::Globalization;

ref class myCultureComparer : public IEqualityComparer
{
public:
    CaseInsensitiveComparer^ myComparer;

public:
    myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer::DefaultInvariant;
    }

public:
    myCultureComparer(CultureInfo^ myCulture)
    {
        myComparer = gcnew CaseInsensitiveComparer(myCulture);
    }

public:
    virtual bool Equals(Object^ x, Object^ y)
    {
        if (myComparer->Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

public:
    virtual int GetHashCode(Object^ obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj->ToString()->ToLower()->GetHashCode();
    }
};

public ref class SamplesHashtable
{

public:
    static void Main()
    {
        // Create a hash table using the default comparer.
        Hashtable^ myHT1 = gcnew Hashtable(3);
        myHT1->Add("FIRST", "Hello");
        myHT1->Add("SECOND", "World");
        myHT1->Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable^ myHT2 = gcnew Hashtable(3, gcnew myCultureComparer());
        myHT2->Add("FIRST", "Hello");
        myHT2->Add("SECOND", "World");
        myHT2->Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo^ myCul = gcnew CultureInfo("tr-TR");
        Hashtable^ myHT3 = gcnew Hashtable(3, gcnew myCultureComparer(myCul));
        myHT3->Add("FIRST", "Hello");
        myHT3->Add("SECOND", "World");
        myHT3->Add("THIRD", "!");

        // Search for a key in each hash table.
        Console::WriteLine("first is in myHT1: {0}", myHT1->ContainsKey("first"));
        Console::WriteLine("first is in myHT2: {0}", myHT2->ContainsKey("first"));
        Console::WriteLine("first is in myHT3: {0}", myHT3->ContainsKey("first"));

    }
};

int main()
{
    SamplesHashtable::Main();
}

/* 
This code produces the following output.  Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/
using System;
using System.Collections;
using System.Globalization;

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

    public myCultureComparer()
    {
        myComparer = CaseInsensitiveComparer.DefaultInvariant;
    }

    public myCultureComparer(CultureInfo myCulture)
    {
        myComparer = new CaseInsensitiveComparer(myCulture);
    }

    public new bool Equals(object x, object y)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public int GetHashCode(object obj)
    {
        // Compare the hash code for the lowercase versions of the strings.
        return obj.ToString().ToLower().GetHashCode();
    }
}

public class SamplesHashtable
{

    public static void Main()
    {

        // Create a hash table using the default comparer.
        Hashtable myHT1 = new Hashtable(3);
        myHT1.Add("FIRST", "Hello");
        myHT1.Add("SECOND", "World");
        myHT1.Add("THIRD", "!");

        // Create a hash table using the specified IEqualityComparer that uses
        // the CaseInsensitiveComparer.DefaultInvariant to determine equality.
        Hashtable myHT2 = new Hashtable(3, new myCultureComparer());
        myHT2.Add("FIRST", "Hello");
        myHT2.Add("SECOND", "World");
        myHT2.Add("THIRD", "!");

        // Create a hash table using an IEqualityComparer that is based on
        // the Turkish culture (tr-TR) where "I" is not the uppercase
        // version of "i".
        CultureInfo myCul = new CultureInfo("tr-TR");
        Hashtable myHT3 = new Hashtable(3, new myCultureComparer(myCul));
        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

        // Search for a key in each hash table.
        Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"));
        Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"));
        Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"));
    }
}


/*
This code produces the following output.
Results vary depending on the system's culture settings.

first is in myHT1: False
first is in myHT2: True
first is in myHT3: False

*/

Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

    Public Sub New()
        myComparer = CaseInsensitiveComparer.DefaultInvariant
    End Sub

    Public Sub New(ByVal myCulture As CultureInfo)
        myComparer = New CaseInsensitiveComparer(myCulture)
    End Sub

    Public Function Equals1(ByVal x As Object, ByVal y As Object) _
        As Boolean Implements IEqualityComparer.Equals

        If (myComparer.Compare(x, y) = 0) Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Function GetHashCode1(ByVal obj As Object) _
        As Integer Implements IEqualityComparer.GetHashCode
        Return obj.ToString().ToLower().GetHashCode()
    End Function
End Class

Public Class SamplesHashtable   

   Public Shared Sub Main()

      ' Create a hash table using the default comparer.
      Dim myHT1 As New Hashtable(3)
      myHT1.Add("FIRST", "Hello")
      myHT1.Add("SECOND", "World")
      myHT1.Add("THIRD", "!")

      ' Create a hash table using the specified IEqualityComparer that uses
      ' the CaseInsensitiveComparer.DefaultInvariant to determine equality.
      Dim myHT2 As New Hashtable(3, New myCultureComparer())
      myHT2.Add("FIRST", "Hello")
      myHT2.Add("SECOND", "World")
      myHT2.Add("THIRD", "!")

      ' Create a hash table using an IEqualityComparer that is based on
      ' the Turkish culture (tr-TR) where "I" is not the uppercase
      ' version of "i".
      Dim myCul As New CultureInfo("tr-TR")
      Dim myHT3 As New Hashtable(3, New myCultureComparer(myCul))
      myHT3.Add("FIRST", "Hello")
      myHT3.Add("SECOND", "World")
      myHT3.Add("THIRD", "!")

      ' Search for a key in each hash table.
      Console.WriteLine("first is in myHT1: {0}", myHT1.ContainsKey("first"))
      Console.WriteLine("first is in myHT2: {0}", myHT2.ContainsKey("first"))
      Console.WriteLine("first is in myHT3: {0}", myHT3.ContainsKey("first"))

   End Sub

End Class


'This code produces the following output.
'Results vary depending on the system's culture settings.
'
'first is in myHT1: False
'first is in myHT2: True
'first is in myHT3: False

Comentarios

Al especificar la capacidad inicial, se elimina la necesidad de realizar una serie de operaciones de cambio de tamaño al agregar elementos al Hashtable objeto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacidad aumenta automáticamente según sea necesario según el factor de carga.Capacity is automatically increased as required based on the load factor.

El factor de carga es la relación máxima de los elementos con los cubos.The load factor is the maximum ratio of elements to buckets. Un factor de carga más pequeño significa una búsqueda más rápida a costa de un aumento del consumo de memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Cuando el factor de carga real alcanza el factor de carga especificado, el número de depósitos se incrementa automáticamente al número primo menor que sea superior al doble del número actual de cubos.When the actual load factor reaches the specified load factor, the number of buckets is automatically increased to the smallest prime number that is larger than twice the current number of buckets.

El IEqualityComparer objeto incluye el proveedor de código hash y el comparador.The IEqualityComparer object includes both the hash code provider and the comparer. Si IEqualityComparer se utiliza un en el Hashtable constructor, no es necesario que los objetos utilizados como claves en Hashtable no reemplacen Object.GetHashCode los Object.Equals métodos y.If an IEqualityComparer is used in the Hashtable constructor, the objects used as keys in the Hashtable are not required to override the Object.GetHashCode and Object.Equals methods.

El proveedor de código hash dispensará los códigos hash de las claves de Hashtable .The hash code provider dispenses hash codes for keys in the Hashtable. El proveedor de código hash predeterminado es la implementación de la clave de Object.GetHashCode .The default hash code provider is the key's implementation of Object.GetHashCode.

El comparador determina si dos claves son iguales.The comparer determines whether two keys are equal. Todas las claves de un Hashtable deben ser únicas.Every key in a Hashtable must be unique. El comparador predeterminado es la implementación de la clave de Object.Equals .The default comparer is the key's implementation of Object.Equals.

IEqualityComparerPermite escenarios como la realización de búsquedas con cadenas que no distinguen mayúsculas de minúsculas.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Este constructor es una O(n) operación, donde n es el capacity parámetro.This constructor is an O(n) operation, where n is the capacity parameter.

Consulte también

Se aplica a