Hashtable Hashtable Hashtable Hashtable Constructors

Definizione

Overload

Hashtable() Hashtable() Hashtable()

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il fattore di carico, il provider di codice hash e l'operatore di confronto predefiniti.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) Hashtable(Int32, Single, IHashCodeProvider, IComparer) Hashtable(Int32, Single, IHashCodeProvider, IComparer) Hashtable(Int32, Single, IHashCodeProvider, IComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il fattore di carico, il provider di codice hash e l'operatore di confronto specificati.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) Hashtable(IDictionary, Single, IHashCodeProvider, IComparer) Hashtable(IDictionary, Single, IHashCodeProvider, IComparer) Hashtable(IDictionary, Single, IHashCodeProvider, IComparer)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico, il provider di codice hash e l'operatore di confronto specificati.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) Hashtable(Int32, Single, IEqualityComparer) Hashtable(Int32, Single, IEqualityComparer) Hashtable(Int32, Single, IEqualityComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il fattore di carico e l'oggetto IEqualityComparer specificati.Initializes a new, empty instance of the Hashtable class using the specified initial capacity, load factor, and IEqualityComparer object.

Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il provider di codice hash e l'operatore di confronto specificati e il fattore di carico predefinito.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) Hashtable(IDictionary, Single, IEqualityComparer) Hashtable(IDictionary, Single, IEqualityComparer) Hashtable(IDictionary, Single, IEqualityComparer)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico e l'oggetto IEqualityComparer specificati.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) Hashtable(IDictionary, IHashCodeProvider, IComparer) Hashtable(IDictionary, IHashCodeProvider, IComparer) Hashtable(IDictionary, IHashCodeProvider, IComparer)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico predefinito e il provider di codice hash e l'operatore di confronto specificati.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. Questa API è obsoleta.This API is obsolete. Per un'alternativa, vedere Hashtable(IDictionary, IEqualityComparer).For an alternative, see Hashtable(IDictionary, IEqualityComparer).

Hashtable(Int32, Single) Hashtable(Int32, Single) Hashtable(Int32, Single) Hashtable(Int32, Single)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e il fattore di carico specificati e il provider di codice hash e l'operatore di confronto predefiniti.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) Hashtable(SerializationInfo, StreamingContext) Hashtable(SerializationInfo, StreamingContext) Hashtable(SerializationInfo, StreamingContext)

Inizializza una nuova istanza vuota della classe Hashtable che è serializzabile tramite gli oggetti SerializationInfo e StreamingContext specificati.Initializes a new, empty instance of the Hashtable class that is serializable using the specified SerializationInfo and StreamingContext objects.

Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e il fattore di carico predefiniti e il provider di codice hash e l'operatore di confronto specificati.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) Hashtable(IDictionary, Single) Hashtable(IDictionary, Single) Hashtable(IDictionary, Single)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico specificato e il provider di codice hash e l'operatore di confronto predefiniti.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) Hashtable(IDictionary, IEqualityComparer) Hashtable(IDictionary, IEqualityComparer) Hashtable(IDictionary, IEqualityComparer)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato in un nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to a new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico predefinito e l'oggetto IEqualityComparer specificato.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) Hashtable(Int32) Hashtable(Int32) Hashtable(Int32)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale specificata e il fattore di carico, il provider di codice hash e l'operatore di confronto predefiniti.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) Hashtable(IEqualityComparer) Hashtable(IEqualityComparer) Hashtable(IEqualityComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e il fattore di carico predefiniti e l'oggetto IEqualityComparer specificato.Initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified IEqualityComparer object.

Hashtable(IDictionary) Hashtable(IDictionary) Hashtable(IDictionary) Hashtable(IDictionary)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico, il provider di codice hash e l'operatore di confronto predefiniti.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) Hashtable(Int32, IEqualityComparer) Hashtable(Int32, IEqualityComparer) Hashtable(Int32, IEqualityComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e l'interfaccia IEqualityComparer specificate e il fattore di carico predefinito.Initializes a new, empty instance of the Hashtable class using the specified initial capacity and IEqualityComparer, and the default load factor.

Hashtable() Hashtable() Hashtable()

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il fattore di carico, il provider di codice hash e l'operatore di confronto predefiniti.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 ()

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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

Commenti

La capacità di una tabella hash viene utilizzata per calcolare il numero ottimale di bucket della tabella hash in base al fattore di carico.A hash table's capacity is used to calculate the optimal number of hash table buckets based on the load factor. La capacità viene aumentata automaticamente in modo obbligatorio.Capacity is automatically increased as required.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtable chiavi nell'oggetto.The hash code provider dispenses hash codes for keys in the Hashtable object. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Questo costruttore è un'operazione O (1).This constructor is an O(1) operation.

Vedi anche

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

Avviso

Questa API è ora obsoleta.

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il fattore di carico, il provider di codice hash e l'operatore di confronto specificati.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);
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)

Parametri

capacity
Int32 Int32 Int32 Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.The approximate number of elements that the Hashtable object can initially contain.

loadFactor
Single Single Single Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. Il risultato è il rapporto massimo tra elementi e bucket.The result is the maximum ratio of elements to buckets.

hcp
IHashCodeProvider IHashCodeProvider IHashCodeProvider IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi in Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable.

-oppure--or- null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer IComparer IComparer IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.The IComparer object to use to determine whether two keys are equal.

-oppure--or- null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.null to use the default comparer, which is each key's implementation of Equals(Object).

Eccezioni

capacity è minore di zero.capacity is less than zero.

-oppure--or- loadFactor è minore di 0,1.loadFactor is less than 0.1.

-oppure--or- loadFactor è maggiore di 1,0.loadFactor is greater than 1.0.

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

Specificando la capacità iniziale si elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Hashtable di elementi all'oggetto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un fattore di carico di 1,0 rappresenta il migliore equilibrio tra velocità e dimensioni.A load factor of 1.0 is the best balance between speed and size.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Il provider di codice hash personalizzato e l'operatore di confronto personalizzato consentono scenari quali eseguire ricerche con stringhe senza distinzione tra maiuscole e minuscole.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Questo costruttore è un'operazione On(), dove n è il capacity parametro.This constructor is an O(n) operation, where n is the capacity parameter.

Vedi anche

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

Avviso

Questa API è ora obsoleta.

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico, il provider di codice hash e l'operatore di confronto specificati.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);
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)

Parametri

d
IDictionary IDictionary IDictionary IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.The IDictionary object to copy to a new Hashtable object.

loadFactor
Single Single Single Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. Il risultato è il rapporto massimo tra elementi e bucket.The result is the maximum ratio of elements to buckets.

hcp
IHashCodeProvider IHashCodeProvider IHashCodeProvider IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi in Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable.

In alternativa-or- null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer IComparer IComparer IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.The IComparer object to use to determine whether two keys are equal.

In alternativa-or- null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.null to use the default comparer, which is each key's implementation of Equals(Object).

Eccezioni

loadFactor è minore di 0,1.loadFactor is less than 0.1.

-oppure--or- loadFactor è maggiore di 1,0.loadFactor is greater than 1.0.

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

La capacità iniziale viene impostata sul numero di elementi nel dizionario di origine.The initial capacity is set to the number of elements in the source dictionary. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un fattore di carico di 1,0 rappresenta il migliore equilibrio tra velocità e dimensioni.A load factor of 1.0 is the best balance between speed and size.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtable chiavi nell'oggetto.The hash code provider dispenses hash codes for keys in the Hashtable object. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Il provider di codice hash personalizzato e l'operatore di confronto personalizzato consentono scenari quali eseguire ricerche con stringhe senza distinzione tra maiuscole e minuscole.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Gli elementi del nuovo Hashtable sono ordinati in base allo stesso ordine in cui l'enumeratore scorre l' IDictionary oggetto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Questo costruttore è un'operazione On(), dove n è il d numero di elementi nel parametro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Hashtable(Int32, Single, IEqualityComparer) Hashtable(Int32, Single, IEqualityComparer) Hashtable(Int32, Single, IEqualityComparer) Hashtable(Int32, Single, IEqualityComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il fattore di carico e l'oggetto IEqualityComparer specificati.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);
new System.Collections.Hashtable : int * single * System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (capacity As Integer, loadFactor As Single, equalityComparer As IEqualityComparer)

Parametri

capacity
Int32 Int32 Int32 Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.The approximate number of elements that the Hashtable object can initially contain.

loadFactor
Single Single Single Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. Il risultato è il rapporto massimo tra elementi e bucket.The result is the maximum ratio of elements to buckets.

equalityComparer
IEqualityComparer IEqualityComparer IEqualityComparer IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.

-oppure--or- null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito.null to use the default hash code provider and the default comparer. Il provider di codice hash predefinito è l'implementazione di GetHashCode() di ogni chiave e l'operatore di confronto predefinito è l'implementazione di Equals(Object) di ogni chiave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Eccezioni

capacity è minore di zero.capacity is less than zero.

-oppure--or- loadFactor è minore di 0,1.loadFactor is less than 0.1.

-oppure--or- loadFactor è maggiore di 1,0.loadFactor is greater than 1.0.

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

Specificando la capacità iniziale si elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Hashtable di elementi all'oggetto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un fattore di carico di 1,0 rappresenta il migliore equilibrio tra velocità e dimensioni.A load factor of 1.0 is the best balance between speed and size.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

L' IEqualityComparer oggetto include il provider di codice hash e l'operatore di confronto.The IEqualityComparer object includes both the hash code provider and the comparer. Se IEqualityComparer Object.Equals Object.GetHashCode Hashtable nel costruttore viene utilizzato un oggetto, gli oggetti utilizzati come chiavi in non devono eseguire l'override dei metodi e. HashtableIf 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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Abilita IEqualityComparer scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Questo costruttore è un'operazione On(), dove n è il capacity parametro.This constructor is an O(n) operation, where n is the capacity parameter.

Vedi anche

Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer) Hashtable(Int32, IHashCodeProvider, IComparer)

Avviso

Questa API è ora obsoleta.

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il provider di codice hash e l'operatore di confronto specificati e il fattore di carico predefinito.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);
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)

Parametri

capacity
Int32 Int32 Int32 Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.The approximate number of elements that the Hashtable object can initially contain.

hcp
IHashCodeProvider IHashCodeProvider IHashCodeProvider IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi in Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable.

-oppure--or- null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer IComparer IComparer IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.The IComparer object to use to determine whether two keys are equal.

-oppure--or- null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.null to use the default comparer, which is each key's implementation of Equals(Object).

Eccezioni

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

Specificando la capacità iniziale si elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Hashtable di elementi all'oggetto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Il provider di codice hash personalizzato e l'operatore di confronto personalizzato consentono scenari quali eseguire ricerche con stringhe senza distinzione tra maiuscole e minuscole.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Questo costruttore è un'operazione On(), dove n è il capacity parametro.This constructor is an O(n) operation, where n is the capacity parameter.

Vedi anche

Hashtable(IDictionary, Single, IEqualityComparer) Hashtable(IDictionary, Single, IEqualityComparer) Hashtable(IDictionary, Single, IEqualityComparer) Hashtable(IDictionary, Single, IEqualityComparer)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico e l'oggetto IEqualityComparer specificati.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);
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)

Parametri

d
IDictionary IDictionary IDictionary IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.The IDictionary object to copy to a new Hashtable object.

loadFactor
Single Single Single Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. Il risultato è il rapporto massimo tra elementi e bucket.The result is the maximum ratio of elements to buckets.

equalityComparer
IEqualityComparer IEqualityComparer IEqualityComparer IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.

In alternativa-or- null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito.null to use the default hash code provider and the default comparer. Il provider di codice hash predefinito è l'implementazione di GetHashCode() di ogni chiave e l'operatore di confronto predefinito è l'implementazione di Equals(Object) di ogni chiave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Eccezioni

loadFactor è minore di 0,1.loadFactor is less than 0.1.

In alternativa-or- loadFactor è maggiore di 1,0.loadFactor is greater than 1.0.

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

La capacità iniziale viene impostata sul numero di elementi nel dizionario di origine.The initial capacity is set to the number of elements in the source dictionary. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un fattore di carico di 1,0 rappresenta il migliore equilibrio tra velocità e dimensioni.A load factor of 1.0 is the best balance between speed and size.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

L' IEqualityComparer oggetto include il provider di codice hash e l'operatore di confronto.The IEqualityComparer object includes both the hash code provider and the comparer. Se IEqualityComparer Object.Equals Object.GetHashCode Hashtable nel costruttore viene utilizzato un oggetto, gli oggetti utilizzati come chiavi nell'oggetto non devono eseguire l'override dei metodi e. HashtableIf 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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Abilita IEqualityComparer scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Gli elementi del nuovo Hashtable sono ordinati in base allo stesso ordine in cui l'enumeratore scorre l' IDictionary oggetto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Questo costruttore è un'operazione On(), dove n è il d numero di elementi nel parametro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Vedi anche

Hashtable(IDictionary, IHashCodeProvider, IComparer) Hashtable(IDictionary, IHashCodeProvider, IComparer) Hashtable(IDictionary, IHashCodeProvider, IComparer) Hashtable(IDictionary, IHashCodeProvider, IComparer)

Avviso

Questa API è ora obsoleta.

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico predefinito e il provider di codice hash e l'operatore di confronto specificati.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. Questa API è obsoleta.This API is obsolete. Per un'alternativa, vedere 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);
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)

Parametri

d
IDictionary IDictionary IDictionary IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.The IDictionary object to copy to a new Hashtable object.

hcp
IHashCodeProvider IHashCodeProvider IHashCodeProvider IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi in Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable.

-oppure--or- null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer IComparer IComparer IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.The IComparer object to use to determine whether two keys are equal.

-oppure--or- null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.null to use the default comparer, which is each key's implementation of Equals(Object).

Eccezioni

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

La capacità iniziale viene impostata sul numero di elementi nel dizionario di origine.The initial capacity is set to the number of elements in the source dictionary. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtable chiavi nell'oggetto.The hash code provider dispenses hash codes for keys in the Hashtable object. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Il provider di codice hash personalizzato e l'operatore di confronto personalizzato consentono scenari quali eseguire ricerche con stringhe senza distinzione tra maiuscole e minuscole.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Gli elementi del nuovo Hashtable sono ordinati in base allo stesso ordine in cui l'enumeratore scorre l' IDictionary oggetto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Questo costruttore è un'operazione On(), dove n è il d numero di elementi nel parametro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Vedi anche

Hashtable(Int32, Single) Hashtable(Int32, Single) Hashtable(Int32, Single) Hashtable(Int32, Single)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e il fattore di carico specificati e il provider di codice hash e l'operatore di confronto predefiniti.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)

Parametri

capacity
Int32 Int32 Int32 Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.The approximate number of elements that the Hashtable object can initially contain.

loadFactor
Single Single Single Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. Il risultato è il rapporto massimo tra elementi e bucket.The result is the maximum ratio of elements to buckets.

Eccezioni

capacity è minore di zero.capacity is less than zero.

-oppure--or- loadFactor è minore di 0,1.loadFactor is less than 0.1.

In alternativa-or- loadFactor è maggiore di 1,0.loadFactor is greater than 1.0.

capacity sta causando un overflow.capacity is causing an overflow.

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

Specificando la capacità iniziale si elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Hashtable di elementi all'oggetto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un fattore di carico di 1,0 rappresenta il migliore equilibrio tra velocità e dimensioni.A load factor of 1.0 is the best balance between speed and size.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Questo costruttore è un'operazione On(), dove n è il capacity parametro.This constructor is an O(n) operation, where n is the capacity parameter.

Vedi anche

Hashtable(SerializationInfo, StreamingContext) Hashtable(SerializationInfo, StreamingContext) Hashtable(SerializationInfo, StreamingContext) Hashtable(SerializationInfo, StreamingContext)

Inizializza una nuova istanza vuota della classe Hashtable che è serializzabile tramite gli oggetti SerializationInfo e StreamingContext specificati.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)

Parametri

info
SerializationInfo SerializationInfo SerializationInfo SerializationInfo

Oggetto SerializationInfo contenente le informazioni necessarie per serializzare l'oggetto Hashtable.A SerializationInfo object containing the information required to serialize the Hashtable object.

context
StreamingContext StreamingContext StreamingContext StreamingContext

Oggetto StreamingContext contenente l'origine e la destinazione del flusso serializzato associato a Hashtable.A StreamingContext object containing the source and destination of the serialized stream associated with the Hashtable.

Eccezioni

Commenti

La capacità di una tabella hash viene utilizzata per calcolare il numero ottimale di bucket della tabella hash in base al fattore di carico.A hash table's capacity is used to calculate the optimal number of hash table buckets based on the load factor. La capacità viene aumentata automaticamente in modo obbligatorio.Capacity is automatically increased as required.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtable chiavi nell'oggetto.The hash code provider dispenses hash codes for keys in the Hashtable object. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Questo costruttore è un'operazione On(), dove n è Count.This constructor is an O(n) operation, where n is Count.

Poiché la serializzazione e la deserializzazione di un Hashtable enumeratore per un oggetto può causare il riordinamento degli elementi, non è possibile continuare l'enumerazione senza Reset chiamare il metodo.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.

Vedi anche

Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer) Hashtable(IHashCodeProvider, IComparer)

Avviso

Questa API è ora obsoleta.

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e il fattore di carico predefiniti e il provider di codice hash e l'operatore di confronto specificati.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);
new System.Collections.Hashtable : System.Collections.IHashCodeProvider * System.Collections.IComparer -> System.Collections.Hashtable
Public Sub New (hcp As IHashCodeProvider, comparer As IComparer)

Parametri

hcp
IHashCodeProvider IHashCodeProvider IHashCodeProvider IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi dell'oggetto Hashtable.The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable object.

In alternativa-or- null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().null to use the default hash code provider, which is each key's implementation of GetHashCode().

comparer
IComparer IComparer IComparer IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.The IComparer object to use to determine whether two keys are equal.

-oppure--or- null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.null to use the default comparer, which is each key's implementation of Equals(Object).

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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

Commenti

La capacità di una tabella hash viene utilizzata per calcolare il numero ottimale di bucket della tabella hash in base al fattore di carico.A hash table's capacity is used to calculate the optimal number of hash table buckets based on the load factor. La capacità viene aumentata automaticamente in modo obbligatorio.Capacity is automatically increased as required.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtable chiavi nell'oggetto.The hash code provider dispenses hash codes for keys in the Hashtable object. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Il provider di codice hash personalizzato e l'operatore di confronto personalizzato consentono scenari quali eseguire ricerche con stringhe senza distinzione tra maiuscole e minuscole.The custom hash code provider and the custom comparer enable scenarios such as doing lookups with case-insensitive strings.

Questo costruttore è un'operazione O (1).This constructor is an O(1) operation.

Vedi anche

Hashtable(IDictionary, Single) Hashtable(IDictionary, Single) Hashtable(IDictionary, Single) Hashtable(IDictionary, Single)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico specificato e il provider di codice hash e l'operatore di confronto predefiniti.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)

Parametri

d
IDictionary IDictionary IDictionary IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.The IDictionary object to copy to a new Hashtable object.

loadFactor
Single Single Single Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori.A number in the range from 0.1 through 1.0 that is multiplied by the default value which provides the best performance. Il risultato è il rapporto massimo tra elementi e bucket.The result is the maximum ratio of elements to buckets.

Eccezioni

loadFactor è minore di 0,1.loadFactor is less than 0.1.

In alternativa-or- loadFactor è maggiore di 1,0.loadFactor is greater than 1.0.

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

La capacità iniziale viene impostata sul numero di elementi nel dizionario di origine.The initial capacity is set to the number of elements in the source dictionary. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption. Un fattore di carico di 1,0 rappresenta il migliore equilibrio tra velocità e dimensioni.A load factor of 1.0 is the best balance between speed and size.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtable chiavi nell'oggetto.The hash code provider dispenses hash codes for keys in the Hashtable object. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Gli elementi del nuovo Hashtable sono ordinati in base allo stesso ordine in cui l'enumeratore scorre l' IDictionary oggetto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Questo costruttore è un'operazione On(), dove n è il d numero di elementi nel parametro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Vedi anche

Hashtable(IDictionary, IEqualityComparer) Hashtable(IDictionary, IEqualityComparer) Hashtable(IDictionary, IEqualityComparer) Hashtable(IDictionary, IEqualityComparer)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato in un nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to a new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico predefinito e l'oggetto IEqualityComparer specificato.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);
new System.Collections.Hashtable : System.Collections.IDictionary * System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (d As IDictionary, equalityComparer As IEqualityComparer)

Parametri

d
IDictionary IDictionary IDictionary IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.The IDictionary object to copy to a new Hashtable object.

equalityComparer
IEqualityComparer IEqualityComparer IEqualityComparer IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.

-oppure--or- null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito.null to use the default hash code provider and the default comparer. Il provider di codice hash predefinito è l'implementazione di GetHashCode() di ogni chiave e l'operatore di confronto predefinito è l'implementazione di Equals(Object) di ogni chiave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Eccezioni

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

La capacità iniziale viene impostata sul numero di elementi nel dizionario di origine.The initial capacity is set to the number of elements in the source dictionary. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

L' IEqualityComparer oggetto include il provider di codice hash e l'operatore di confronto.The IEqualityComparer object includes both the hash code provider and the comparer. Se IEqualityComparer Object.Equals Object.GetHashCode Hashtable nel costruttore viene utilizzato un oggetto, gli oggetti utilizzati come chiavi nell'oggetto non devono eseguire l'override dei metodi e. HashtableIf 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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Abilita IEqualityComparer scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Gli elementi del nuovo Hashtable sono ordinati in base allo stesso ordine in cui l'enumeratore scorre l' IDictionary oggetto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Questo costruttore è un'operazione On(), dove n è il d numero di elementi nel parametro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Vedi anche

Hashtable(Int32) Hashtable(Int32) Hashtable(Int32) Hashtable(Int32)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale specificata e il fattore di carico, il provider di codice hash e l'operatore di confronto predefiniti.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)

Parametri

capacity
Int32 Int32 Int32 Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.The approximate number of elements that the Hashtable object can initially contain.

Eccezioni

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

Specificando la capacità iniziale si elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Hashtable di elementi all'oggetto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Questo costruttore è un'operazione On(), dove n è capacity.This constructor is an O(n) operation, where n is capacity.

Vedi anche

Hashtable(IEqualityComparer) Hashtable(IEqualityComparer) Hashtable(IEqualityComparer) Hashtable(IEqualityComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e il fattore di carico predefiniti e l'oggetto IEqualityComparer specificato.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);
new System.Collections.Hashtable : System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (equalityComparer As IEqualityComparer)

Parametri

equalityComparer
IEqualityComparer IEqualityComparer IEqualityComparer IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con l'oggetto Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable object.

-oppure--or- null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito.null to use the default hash code provider and the default comparer. Il provider di codice hash predefinito è l'implementazione di GetHashCode() di ogni chiave e l'operatore di confronto predefinito è l'implementazione di Equals(Object) di ogni chiave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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

Commenti

La capacità di una tabella hash viene utilizzata per calcolare il numero ottimale di bucket della tabella hash in base al fattore di carico.A hash table's capacity is used to calculate the optimal number of hash table buckets based on the load factor. La capacità viene aumentata automaticamente in modo obbligatorio.Capacity is automatically increased as required.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

L' IEqualityComparer oggetto include il provider di codice hash e l'operatore di confronto.The IEqualityComparer object includes both the hash code provider and the comparer. Se IEqualityComparer Object.Equals Object.GetHashCode Hashtable nel costruttore viene utilizzato un oggetto, gli oggetti utilizzati come chiavi nell'oggetto non devono eseguire l'override dei metodi e. HashtableIf 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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Abilita IEqualityComparer scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Questo costruttore è un'operazione O (1).This constructor is an O(1) operation.

Vedi anche

Hashtable(IDictionary) Hashtable(IDictionary) Hashtable(IDictionary) Hashtable(IDictionary)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable.Initializes a new instance of the Hashtable class by copying the elements from the specified dictionary to the new Hashtable object. Il nuovo oggetto Hashtable ha una capacità iniziale uguale al numero di elementi copiati e usa il fattore di carico, il provider di codice hash e l'operatore di confronto predefiniti.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)

Parametri

d
IDictionary IDictionary IDictionary IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.The IDictionary object to copy to a new Hashtable object.

Eccezioni

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

La capacità iniziale viene impostata sul numero di elementi nel dizionario di origine.The initial capacity is set to the number of elements in the source dictionary. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

Il provider di codice hash distribuisce i codici hash per le Hashtable chiavi nell'oggetto.The hash code provider dispenses hash codes for keys in the Hashtable object. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Gli elementi del nuovo Hashtable sono ordinati in base allo stesso ordine in cui l'enumeratore scorre l' IDictionary oggetto.The elements of the new Hashtable are sorted in the same order in which the enumerator iterates through the IDictionary object.

Questo costruttore è un'operazione On(), dove n è il d numero di elementi nel parametro.This constructor is an O(n) operation, where n is the number of elements in the d parameter.

Vedi anche

Hashtable(Int32, IEqualityComparer) Hashtable(Int32, IEqualityComparer) Hashtable(Int32, IEqualityComparer) Hashtable(Int32, IEqualityComparer)

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e l'interfaccia IEqualityComparer specificate e il fattore di carico predefinito.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);
new System.Collections.Hashtable : int * System.Collections.IEqualityComparer -> System.Collections.Hashtable
Public Sub New (capacity As Integer, equalityComparer As IEqualityComparer)

Parametri

capacity
Int32 Int32 Int32 Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.The approximate number of elements that the Hashtable object can initially contain.

equalityComparer
IEqualityComparer IEqualityComparer IEqualityComparer IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con Hashtable.The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.

In alternativa-or- null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito.null to use the default hash code provider and the default comparer. Il provider di codice hash predefinito è l'implementazione di GetHashCode() di ogni chiave e l'operatore di confronto predefinito è l'implementazione di Equals(Object) di ogni chiave.The default hash code provider is each key's implementation of GetHashCode() and the default comparer is each key's implementation of Equals(Object).

Eccezioni

Esempi

Nell'esempio di codice seguente vengono create tabelle hash Hashtable usando costruttori diversi e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ciascuna di esse contiene gli stessi elementi.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 'Main 

End Class 'SamplesHashtable


'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

Commenti

Specificando la capacità iniziale si elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta Hashtable di elementi all'oggetto.Specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Hashtable object. La capacità viene aumentata automaticamente come richiesto in base al fattore di carico.Capacity is automatically increased as required based on the load factor.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket.The load factor is the maximum ratio of elements to buckets. Un fattore di carico più piccolo significa una ricerca più veloce a scapito di un aumento del consumo di memoria.A smaller load factor means faster lookup at the cost of increased memory consumption.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo più grande del doppio del numero corrente di bucket.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.

L' IEqualityComparer oggetto include il provider di codice hash e l'operatore di confronto.The IEqualityComparer object includes both the hash code provider and the comparer. Se IEqualityComparer Object.Equals Object.GetHashCode Hashtable nel costruttore viene utilizzato un oggetto, gli oggetti utilizzati come chiavi in non devono eseguire l'override dei metodi e. HashtableIf 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.

Il provider di codice hash distribuisce i codici hash per le Hashtablechiavi in.The hash code provider dispenses hash codes for keys in the Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave Object.GetHashCodedi.The default hash code provider is the key's implementation of Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali.The comparer determines whether two keys are equal. Ogni chiave in un Hashtable deve essere univoca.Every key in a Hashtable must be unique. L'operatore di confronto predefinito è l'implementazione della chiave Object.Equalsdi.The default comparer is the key's implementation of Object.Equals.

Abilita IEqualityComparer scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.The IEqualityComparer enables scenarios such as doing lookups with case-insensitive strings.

Questo costruttore è un'operazione On(), dove n è il capacity parametro.This constructor is an O(n) operation, where n is the capacity parameter.

Vedi anche

Si applica a