Hashtable Costruttori

Definizione

Inizializza una nuova istanza della classe Hashtable.

Overload

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.

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

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.

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

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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.

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.

Hashtable(Int32, IHashCodeProvider, IComparer)
Obsoleti.
Obsoleti.

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.

Hashtable(IDictionary, Single, IEqualityComparer)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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.

Hashtable(IDictionary, IHashCodeProvider, IComparer)
Obsoleti.
Obsoleti.

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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. Questa API è obsoleta. Per un'alternativa, vedere Hashtable(IDictionary, IEqualityComparer).

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.

Hashtable(SerializationInfo, StreamingContext)
Obsoleti.

Inizializza una nuova istanza vuota della classe Hashtable che è serializzabile tramite gli oggetti SerializationInfo e StreamingContext specificati.

Hashtable(IHashCodeProvider, IComparer)
Obsoleti.
Obsoleti.
Obsoleti.

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.

Hashtable(IDictionary, Single)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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.

Hashtable(IDictionary, IEqualityComparer)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato in un nuovo oggetto Hashtable. 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.

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.

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.

Hashtable(IDictionary)

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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.

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.

Hashtable()

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

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.

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

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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 usata per calcolare il numero ottimale di bucket di tabelle hash in base al fattore di carico. La capacità viene aumentata automaticamente in base alle esigenze.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket. Un fattore di carico più piccolo implica una ricerca più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore del doppio del numero corrente di bucket.

Il provider di codice hash distribuisce i codici hash per le chiavi nell'oggetto Hashtable . Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. L'operatore di confronto predefinito è l'implementazione della chiave di Object.Equals.

Questo costruttore è un'operazione O(1) .

Vedi anche

Si applica a

Hashtable(Int32, Single, IHashCodeProvider, IComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Attenzione

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

Attenzione

This constructor has been deprecated. Use Hashtable(int, float, IEqualityComparer) instead.

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.

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

Parametri

capacity
Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.

loadFactor
Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori. Il risultato è il rapporto massimo tra elementi e bucket.

hcp
IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi in Hashtable.

-oppure-

null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().

comparer
IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.

-oppure-

null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.

Attributi

Eccezioni

capacity è minore di zero.

-oppure-

loadFactor è minore di 0,1.

-oppure-

loadFactor è maggiore di 1,0.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

    }
};

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable

    Public Shared Sub Main()

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

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

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

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

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

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

    End Sub

End Class


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

Commenti

Se si specifica la capacità iniziale, si elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto Hashtable . La capacità viene aumentata automaticamente in base al fattore di carico richiesto.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket. Un fattore di carico più piccolo implica una ricerca più rapida del costo dell'aumento del consumo di memoria. Un fattore di carico di 1,0 è il miglior equilibrio tra velocità e dimensioni.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore del doppio del numero corrente di bucket.

Il provider di codice hash distribuisce i codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. L'operatore di confronto predefinito è l'implementazione della chiave di Object.Equals.

Il provider di codice hash personalizzato e l'operatore di confronto personalizzato abilitano scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Questo costruttore è un'operazione O(n) , dove n è il capacity parametro .

Vedi anche

Si applica a

Hashtable(IDictionary, Single, IHashCodeProvider, IComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Attenzione

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

Attenzione

This constructor has been deprecated. Use Hashtable(IDictionary, float, IEqualityComparer) instead.

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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.

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

Parametri

d
IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.

loadFactor
Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori. Il risultato è il rapporto massimo tra elementi e bucket.

hcp
IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi in Hashtable.

-oppure-

null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().

comparer
IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.

-oppure-

null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.

Attributi

Eccezioni

loadFactor è minore di 0,1.

-oppure-

loadFactor è maggiore di 1,0.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

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

   End Sub

End Class


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

Commenti

La capacità iniziale è impostata sul numero di elementi nel dizionario di origine. La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria. Un fattore di carico pari a 1,0 è il migliore equilibrio tra velocità e dimensioni.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

Il provider di codice hash distribuisce codici hash per le chiavi nell'oggetto Hashtable . Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Il provider di codice hash personalizzato e il comparer personalizzato abilitano scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Gli elementi del nuovo Hashtable vengono ordinati nello stesso ordine in cui l'enumeratore esegue l'iterazione tramite l'oggetto IDictionary .

Questo costruttore è un'operazione O(n) , dove n è il numero di elementi nel d parametro.

Si applica a

Hashtable(Int32, Single, IEqualityComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale, il fattore di carico e l'oggetto IEqualityComparer specificati.

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

Parametri

capacity
Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.

loadFactor
Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori. Il risultato è il rapporto massimo tra elementi e bucket.

equalityComparer
IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con Hashtable.

-oppure-

null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito. 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.

Eccezioni

capacity è minore di zero.

-oppure-

loadFactor è minore di 0,1.

-oppure-

loadFactor è maggiore di 1,0.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

    }
};

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable

    Public Shared Sub Main()

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

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

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

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

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

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

    End Sub

End Class


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

Commenti

Se si specifica la capacità iniziale, la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto Hashtable . La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria. Un fattore di carico pari a 1,0 è il migliore equilibrio tra velocità e dimensioni.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

L'oggetto IEqualityComparer include sia il provider di codice hash che il comparer. Se un IEqualityComparer oggetto viene usato nel costruttore, gli oggetti usati come chiavi nell'oggetto HashtableHashtable non sono necessari per eseguire l'override dei Object.GetHashCode metodi e Object.Equals .

Il provider di codice hash distribuisce codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Consente scenari come l'operazione IEqualityComparer di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Questo costruttore è un'operazione O(n) , dove n è il capacity parametro .

Vedi anche

Si applica a

Hashtable(Int32, IHashCodeProvider, IComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Attenzione

Please use Hashtable(int, IEqualityComparer) instead.

Attenzione

This constructor has been deprecated. Use Hashtable(int, IEqualityComparer) instead.

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.

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

Parametri

capacity
Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.

hcp
IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi in Hashtable.

-oppure-

null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().

comparer
IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.

-oppure-

null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.

Attributi

Eccezioni

capacity è minore di zero.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

    }
};

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

   End Sub

End Class


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

Commenti

Se si specifica la capacità iniziale, la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto Hashtable . La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

Il provider di codice hash distribuisce codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Il provider di codice hash personalizzato e il comparer personalizzato abilitano scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Questo costruttore è un'operazione O(n) , dove n è il capacity parametro .

Vedi anche

Si applica a

Hashtable(IDictionary, Single, IEqualityComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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.

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

Parametri

d
IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.

loadFactor
Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori. Il risultato è il rapporto massimo tra elementi e bucket.

equalityComparer
IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con Hashtable.

-oppure-

null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito. 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.

Eccezioni

loadFactor è minore di 0,1.

-oppure-

loadFactor è maggiore di 1,0.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

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

   End Sub

End Class


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

Commenti

La capacità iniziale è impostata sul numero di elementi nel dizionario di origine. La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria. Un fattore di carico pari a 1,0 è il migliore equilibrio tra velocità e dimensioni.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

L'oggetto IEqualityComparer include sia il provider di codice hash che il comparer. Se un IEqualityComparer oggetto viene usato nel Hashtable costruttore, gli oggetti usati come chiavi nell'oggetto non sono necessari per eseguire l'override Hashtable dei Object.GetHashCode metodi e Object.Equals .

Il provider di codice hash distribuisce codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. L'operatore di confronto predefinito è l'implementazione della chiave di Object.Equals.

Abilita scenari come l'operazione IEqualityComparer di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Gli elementi del nuovo Hashtable vengono ordinati nello stesso ordine in cui l'enumeratore scorre l'oggetto IDictionary .

Questo costruttore è un'operazione O(n) , dove n è il numero di elementi nel d parametro .

Vedi anche

Si applica a

Hashtable(IDictionary, IHashCodeProvider, IComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Attenzione

Please use Hashtable(IDictionary, IEqualityComparer) instead.

Attenzione

This constructor has been deprecated. Use Hashtable(IDictionary, IEqualityComparer) instead.

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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. Questa API è obsoleta. Per un'alternativa, vedere Hashtable(IDictionary, IEqualityComparer).

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

Parametri

d
IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.

hcp
IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi in Hashtable.

-oppure-

null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().

comparer
IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.

-oppure-

null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.

Attributi

Eccezioni

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

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

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

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

   End Sub

End Class


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

Commenti

La capacità iniziale viene impostata sul numero di elementi nel dizionario di origine. La capacità viene aumentata automaticamente in base al fattore di carico richiesto.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket. Un fattore di carico più piccolo implica una ricerca più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore del doppio del numero corrente di bucket.

Il provider di codice hash distribuisce i codici hash per le chiavi nell'oggetto Hashtable . Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. L'operatore di confronto predefinito è l'implementazione della chiave di Object.Equals.

Il provider di codice hash personalizzato e l'operatore di confronto personalizzato abilitano scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Gli elementi del nuovo Hashtable vengono ordinati nello stesso ordine in cui l'enumeratore scorre l'oggetto IDictionary .

Questo costruttore è un'operazione O(n) , dove n è il numero di elementi nel d parametro .

Vedi anche

Si applica a

Hashtable(Int32, Single)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

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.

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

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.

loadFactor
Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori. Il risultato è il rapporto massimo tra elementi e bucket.

Eccezioni

capacity è minore di zero.

-oppure-

loadFactor è minore di 0,1.

-oppure-

loadFactor è maggiore di 1,0.

capacity sta causando un overflow.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

    }
};

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable

    Public Shared Sub Main()

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

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

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

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

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

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

    End Sub

End Class


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

Commenti

Se si specifica la capacità iniziale, si elimina la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto Hashtable . La capacità viene aumentata automaticamente in base al fattore di carico richiesto.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket. Un fattore di carico più piccolo implica una ricerca più rapida del costo dell'aumento del consumo di memoria. Un fattore di carico di 1,0 è il miglior equilibrio tra velocità e dimensioni.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore del doppio del numero corrente di bucket.

Il provider di codice hash distribuisce i codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. L'operatore di confronto predefinito è l'implementazione della chiave di Object.Equals.

Questo costruttore è un'operazione O(n) , dove n è il capacity parametro .

Vedi anche

Si applica a

Hashtable(SerializationInfo, StreamingContext)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Attenzione

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

Inizializza una nuova istanza vuota della classe Hashtable che è serializzabile tramite gli oggetti SerializationInfo e StreamingContext specificati.

protected:
 Hashtable(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Hashtable (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
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
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
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

Oggetto SerializationInfo contenente le informazioni necessarie per serializzare l'oggetto Hashtable.

context
StreamingContext

Oggetto StreamingContext contenente l'origine e la destinazione del flusso serializzato associato a Hashtable.

Attributi

Eccezioni

info è null.

Commenti

La capacità di una tabella hash viene usata per calcolare il numero ottimale di bucket di tabelle hash in base al fattore di carico. La capacità viene aumentata automaticamente in base alle esigenze.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket. Un fattore di carico più piccolo implica una ricerca più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore del doppio del numero corrente di bucket.

Il provider di codice hash distribuisce i codici hash per le chiavi nell'oggetto Hashtable . Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. L'operatore di confronto predefinito è l'implementazione della chiave di Object.Equals.

Questo costruttore è un'operazione O(n) , dove n è Count.

Poiché la serializzazione e la deserializzazione di un enumeratore per un Hashtable oggetto possono causare la riordinamento degli elementi, non è possibile continuare l'enumerazione senza chiamare il Reset metodo .

Vedi anche

Si applica a

Hashtable(IHashCodeProvider, IComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Attenzione

Please use Hashtable(IEqualityComparer) instead.

Attenzione

This constructor has been deprecated. Use Hashtable(IEqualityComparer).

Attenzione

This constructor has been deprecated. Use Hashtable(IEqualityComparer) instead.

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.

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

Parametri

hcp
IHashCodeProvider

Oggetto IHashCodeProvider che fornisce i codici hash per tutte le chiavi dell'oggetto Hashtable.

-oppure-

null per usare il provider predefinito di codice hash, che rappresenta l'implementazione di ogni chiave di GetHashCode().

comparer
IComparer

Oggetto IComparer da usare per determinare se due chiavi sono uguali.

-oppure-

null per usare l'operatore di confronto predefinito, che rappresenta l'implementazione del metodo Equals(Object) di ogni chiave.

Attributi

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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 usata per calcolare il numero ottimale di bucket di tabelle hash in base al fattore di carico. La capacità viene aumentata automaticamente in base alle esigenze.

Il fattore di carico è il rapporto massimo tra gli elementi e i bucket. Un fattore di carico più piccolo implica una ricerca più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore del doppio del numero corrente di bucket.

Il provider di codice hash distribuisce i codici hash per le chiavi nell'oggetto Hashtable . Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

L'operatore di confronto determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. L'operatore di confronto predefinito è l'implementazione della chiave di Object.Equals.

Il provider di codice hash personalizzato e l'operatore di confronto personalizzato abilitano scenari come l'operazione di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Questo costruttore è un'operazione O(1) .

Vedi anche

Si applica a

Hashtable(IDictionary, Single)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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.

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

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.

loadFactor
Single

Un numero nell'intervallo da 0,1 a 1,0 moltiplicato per il valore predefinito che garantisce le prestazioni migliori. Il risultato è il rapporto massimo tra elementi e bucket.

Eccezioni

loadFactor è minore di 0,1.

-oppure-

loadFactor è maggiore di 1,0.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

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

   End Sub

End Class


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

Commenti

La capacità iniziale viene impostata sul numero di elementi nel dizionario di origine. La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria. Un fattore di carico pari a 1,0 è il migliore equilibrio tra velocità e dimensioni.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

Il provider di codice hash distribuisce codici hash per le chiavi nell'oggetto Hashtable . Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Gli elementi del nuovo Hashtable vengono ordinati nello stesso ordine in cui l'enumeratore esegue l'iterazione tramite l'oggetto IDictionary .

Questo costruttore è un'operazione O(n) , dove n è il numero di elementi nel d parametro.

Vedi anche

Si applica a

Hashtable(IDictionary, IEqualityComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato in un nuovo oggetto Hashtable. 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.

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

Parametri

d
IDictionary

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.

equalityComparer
IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con Hashtable.

-oppure-

null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito. 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.

Eccezioni

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

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

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

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

   End Sub

End Class


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

Commenti

La capacità iniziale è impostata sul numero di elementi nel dizionario di origine. La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

L'oggetto IEqualityComparer include sia il provider di codice hash che il comparer. Se un IEqualityComparer oggetto viene usato nel Hashtable costruttore, gli oggetti usati come chiavi nell'oggetto non sono necessari per eseguire l'override Hashtable dei Object.GetHashCode metodi e Object.Equals .

Il provider di codice hash distribuisce codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Consente scenari come l'operazione IEqualityComparer di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Gli elementi del nuovo Hashtable vengono ordinati nello stesso ordine in cui l'enumeratore esegue l'iterazione tramite l'oggetto IDictionary .

Questo costruttore è un'operazione O(n) , dove n è il numero di elementi nel d parametro.

Vedi anche

Si applica a

Hashtable(Int32)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

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.

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

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.

Eccezioni

capacity è minore di zero.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

    }
};

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

   End Sub

End Class


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

Commenti

Se si specifica la capacità iniziale, la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto Hashtable . La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

Il provider di codice hash distribuisce codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Questo costruttore è un'operazione O(n) , dove n è capacity.

Vedi anche

Si applica a

Hashtable(IEqualityComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e il fattore di carico predefiniti e l'oggetto IEqualityComparer specificato.

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

Parametri

equalityComparer
IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con l'oggetto Hashtable.

-oppure-

null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito. 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.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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 usata per calcolare il numero ottimale di bucket della tabella hash in base al fattore di carico. La capacità viene aumentata automaticamente in base alle esigenze.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

L'oggetto IEqualityComparer include sia il provider di codice hash che il comparer. Se un IEqualityComparer oggetto viene usato nel Hashtable costruttore, gli oggetti usati come chiavi nell'oggetto non sono necessari per eseguire l'override Hashtable dei Object.GetHashCode metodi e Object.Equals .

Il provider di codice hash distribuisce codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Consente scenari come l'operazione IEqualityComparer di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Questo costruttore è un'operazione O(1) .

Vedi anche

Si applica a

Hashtable(IDictionary)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Inizializza una nuova istanza della classe Hashtable copiando gli elementi dal dizionario specificato nel nuovo oggetto Hashtable. 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.

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

Oggetto IDictionary da copiare in un nuovo oggetto Hashtable.

Eccezioni

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

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

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

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

   End Sub

End Class


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

Commenti

La capacità iniziale è impostata sul numero di elementi nel dizionario di origine. La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

Il provider di codice hash distribuisce codici hash per le chiavi nell'oggetto Hashtable . Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Gli elementi del nuovo Hashtable vengono ordinati nello stesso ordine in cui l'enumeratore esegue l'iterazione tramite l'oggetto IDictionary .

Questo costruttore è un'operazione O(n) , dove n è il numero di elementi nel d parametro.

Vedi anche

Si applica a

Hashtable(Int32, IEqualityComparer)

Source:
Hashtable.cs
Source:
Hashtable.cs
Source:
Hashtable.cs

Inizializza una nuova istanza vuota della classe Hashtable usando la capacità iniziale e l'interfaccia IEqualityComparer specificate e il fattore di carico predefinito.

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

Parametri

capacity
Int32

Numero approssimativo di elementi che l'oggetto Hashtable può contenere inizialmente.

equalityComparer
IEqualityComparer

Oggetto IEqualityComparer che definisce il provider di codice hash e l'operatore di confronto da usare con Hashtable.

-oppure-

null per utilizzare il provider predefinito di codice hash e l'operatore di confronto predefinito. 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.

Eccezioni

capacity è minore di zero.

Esempio

Nell'esempio di codice seguente vengono create tabelle hash usando costruttori diversi Hashtable e vengono illustrate le differenze nel comportamento delle tabelle hash, anche se ognuna contiene gli stessi elementi.

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

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

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

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

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

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

public ref class SamplesHashtable
{

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

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

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

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

    }
};

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

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

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

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

class myCultureComparer : IEqualityComparer
{
    public CaseInsensitiveComparer myComparer;

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

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

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

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

public class SamplesHashtable
{

    public static void Main()
    {

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

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

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

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


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

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

*/
Imports System.Collections
Imports System.Globalization

Public Class myCultureComparer
    Implements IEqualityComparer

    Dim myComparer As CaseInsensitiveComparer

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

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

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

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

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

Public Class SamplesHashtable   

   Public Shared Sub Main()

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

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

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

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

   End Sub

End Class


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

Commenti

Se si specifica la capacità iniziale, la necessità di eseguire una serie di operazioni di ridimensionamento durante l'aggiunta di elementi all'oggetto Hashtable . La capacità viene aumentata automaticamente in base al fattore di carico.

Il fattore di carico è il rapporto massimo di elementi a bucket. Un fattore di carico più piccolo significa un'analisi più rapida del costo dell'aumento del consumo di memoria.

Quando il fattore di carico effettivo raggiunge il fattore di carico specificato, il numero di bucket viene automaticamente aumentato al numero primo più piccolo maggiore di due volte il numero corrente di bucket.

L'oggetto IEqualityComparer include sia il provider di codice hash che il comparer. Se un IEqualityComparer oggetto viene usato nel costruttore, gli oggetti usati come chiavi nell'oggetto HashtableHashtable non sono necessari per eseguire l'override dei Object.GetHashCode metodi e Object.Equals .

Il provider di codice hash distribuisce codici hash per le chiavi in Hashtable. Il provider di codice hash predefinito è l'implementazione della chiave di Object.GetHashCode.

Il comparer determina se due chiavi sono uguali. Ogni chiave in un Hashtable deve essere univoca. Il comparer predefinito è l'implementazione della chiave di Object.Equals.

Consente scenari come l'operazione IEqualityComparer di ricerca con stringhe senza distinzione tra maiuscole e minuscole.

Questo costruttore è un'operazione O(n) , dove n è il capacity parametro .

Vedi anche

Si applica a