C# Hashtable Hashtable(IDictionary, IEqualityComparer)
Description
Hashtable Hashtable(IDictionary, IEqualityComparer)
initializes
a new instance of the Hashtable class by copying the elements from the specified
dictionary to a new Hashtable object. The new Hashtable object has an initial
capacity equal to the number of elements copied, and uses the default load
factor and the specified IEqualityComparer object.
Syntax
Hashtable.Hashtable(IDictionary, IEqualityComparer)
has the following syntax.
public Hashtable(
IDictionary d,
IEqualityComparer equalityComparer
)
Parameters
Hashtable.Hashtable(IDictionary, IEqualityComparer)
has the following parameters.
d
- The IDictionary object to copy to a new Hashtable object.equalityComparer
- The IEqualityComparer object that defines the hash code provider and the comparer to use with the Hashtable.equalityComparer
- -or-equalityComparer
- null to use the default hash code provider and the default comparer. The default hash code provider is each key's implementation of Object.GetHashCode and the default comparer 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, even if each one contains the same elements.
using System;/*w w w. j ava 2 s.c o m*/
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()
{
SortedList mySL = new SortedList();
mySL.Add("FIRST", "Hello");
mySL.Add("SECOND", "World");
mySL.Add("THIRD", "!");
Hashtable myHT2 = new Hashtable(mySL, new myCultureComparer());
}
}
The code above generates the following result.