C# Hashtable Hashtable(IHashCodeProvider, IComparer)

Description

Hashtable Hashtable(IHashCodeProvider, IComparer) initializes a new, empty instance of the Hashtable class using the default initial capacity and load factor, and the specified hash code provider and comparer.

Syntax

Hashtable.Hashtable(IHashCodeProvider, IComparer) has the following syntax.


[ObsoleteAttribute("Please use Hashtable(IEqualityComparer) instead.")]
public Hashtable(
  IHashCodeProvider hcp,/*  w w  w  . j a  v  a 2  s .c om*/
  IComparer comparer
)

Parameters

Hashtable.Hashtable(IHashCodeProvider, IComparer) has the following parameters.

  • hcp - The IHashCodeProvider object that supplies the hash codes for all keys in the Hashtable object.
  • hcp - -or-
  • hcp - null to use the default hash code provider, which is each key's implementation of Object.GetHashCode.
  • comparer - The IComparer object to use to determine whether two keys are equal.
  • comparer - -or-
  • comparer - null to use the default comparer, which is each key's implementation of Object.Equals.

Example

The following code example creates hash tables using different Hashtable constructors and demonstrates the differences in the behavior of the hash tables.


using System;//w w w .j a  va2 s .c  o m
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)
    {
        if (myComparer.Compare(x, y) == 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

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

public class SamplesHashtable
{

    public static void Main()
    {
        Hashtable myHT3 = new Hashtable(
            CaseInsensitiveHashCodeProvider.DefaultInvariant,
            CaseInsensitiveComparer.DefaultInvariant);
        myHT3.Add("FIRST", "Hello");
        myHT3.Add("SECOND", "World");
        myHT3.Add("THIRD", "!");

    }

}

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections »




ArrayList
BitArray
Comparer
Hashtable
Queue
SortedList
Stack